--阻塞和错误 --version 2005 declare@tcountint,@rcountint select@tcount=@@trancount if@tcount=0---外部没有事务打开 begintran else savetran s1 --外部事务已经打开 begin try set lock_timeout 5000--5秒超时 select b.text,c.*,d.*from sys.dm_exec_connections as a cross apply sys.dm_exec_sql_text(most_recent_sql_handle) as b innerjoin sys.dm_tran_locks as c on a.session_id=c.request_session_id and request_status='WAIT' innerjoin sys.dm_tran_locks as d on c.resource_database_id=d.resource_database_id and c.resource_associated_entity_id=d.resource_associated_entity_id and d.request_status='GRANT' and c.resource_description=d.resource_description --查看阻塞 select@count=@@rowcount insertinto ..... --语句 if@tcount=0and@count=0 begin committran end end try begin catch if@tcount=0and@count>0--外部事物没打开并且阻塞 begin select b.text,c.*,d.*from sys.dm_exec_connections as a cross apply sys.dm_exec_sql_text(most_recent_sql_handle) as b innerjoin sys.dm_tran_locks as c on a.session_id=c.request_session_id and request_status='WAIT' innerjoin sys.dm_tran_locks as d on c.resource_database_id=d.resource_database_id and c.resource_associated_entity_id=d.resource_associated_entity_id and d.request_status='GRANT' and c.resource_description=d.resource_description --查看阻塞 select error_message(),error_severity(),error_line() rollbacktran end if@tcount>0and@count=0--外部事物打开并且没阻塞 begin if xact_state()=1--事务错误 begin select error_message(),error_severity(),error_line() rollbacktran s1 end if xact_state()=-1--外部事务错误 begin print'外部事务错误 自己判断 committed 或 rollback ' end end if@tcount>0and@count>0 begin select b.text,c.*,d.*from sys.dm_exec_connections as a cross apply sys.dm_exec_sql_text(most_recent_sql_handle) as b innerjoin sys.dm_tran_locks as c on a.session_id=c.request_session_id and request_status='WAIT' innerjoin sys.dm_tran_locks as d on c.resource_database_id=d.resource_database_id and c.resource_associated_entity_id=d.resource_associated_entity_id and d.request_status='GRANT' and c.resource_description=d.resource_description --查看阻塞 if xact_state()=1 begin select error_message(),error_severity(),error_line() rollbacktran s1 end if xact_state()=-1--外部事务错误 begin print'外部事务错误 自己判断 committed 或 rollback ' end end end catch