sqlserver 查询数据库死锁表语句
时间: 2024-08-14 08:09:50 浏览: 144
在SQL Server中,查询数据库死锁信息通常涉及到系统表`sys.dm_tran_locks`和`sys.dm_os_waiting_tasks`。你可以通过以下几个步骤来获取死锁信息:
1. **使用`sys.dm_tran_locks`**:
```sql
SELECT
request_session_id AS 'Session ID',
request_mode AS 'Lock Type',
request_status AS 'Status (WAITING / OWM)',
object_name(resource_database_id, lock_object_address) AS 'Locked Object',
row_count(*) AS 'Rows Affected'
FROM
sys.dm_tran_locks
WHERE
is_rowlock = 1 AND lock_status = 'deadlock';
```
这将返回当前有死锁请求的会话ID、锁定类型、状态以及锁定的对象。
2. **结合`sys.dm_os_waiting_tasks`**:
```sql
SELECT
t1.session_id,
t1.request_mode,
t1.resource_db_id,
t1.resource_transaction_log_sequence AS 'Transaction Sequence',
t1.resource_database_name AS 'Database Name',
t2.object_name AS 'Deadlocked On',
t2.lock_type
FROM
sys.dm_tran_locks t1
INNER JOIN
sys.dm_tran_locks t2 ON t1.holding_session_id = t2.request_session_id
WHERE
t1.is_rowlock = 1 AND t1.lock_status = 'deadlock' AND t2.lock_status = 'wait';
```
这个查询还会显示出导致死锁的另一个事务的信息。
3. **使用`DBCC OPENTRAN`和`KILL`命令**:
如果你需要立即释放死锁,可以先查看哪些事务参与了死锁,然后用`DBCC OPENTRAN`检查事务,并使用`KILL`命令结束它们:
```sql
DBCC OPENTRAN;
KILL <transaction_id>;
```
请务必谨慎操作,因为`KILL`可能会导致数据丢失。
阅读全文