锁的分类:
1. 从数据库系统的角度来看:分为独占锁(即排它锁),共享锁和更新锁
- 共享锁只用于表级,排他锁用于行级。
- 加了共享锁的对象,可以继续加共享锁,不能再加排他锁。加了排他锁后,不能再加任何锁。
2. 从程序员的角度看:分为乐观锁和悲观锁。
- 乐观锁:完全依靠数据库来管理锁的工作。
- 悲观锁:程序员自己管理数据或对象上的锁处理。
MS-SQLSERVER 使用锁在多个同时在数据库内执行修改的用户间实现悲观并发控制
<strong>sql 2008 存储过程检测死锁:</strong>
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_who_lock]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[sp_who_lock] GO use master go create procedure sp_who_lock as begin declare @spid int,@bl int, @intTransactionCountOnEntry
int, @intRowcount int, @intCountProperties int, @intCounter int create table #tmp_lock_who ( id int identity(1,1), spid smallint, bl smallint) IF @@ERROR<>0 RETURN @@ERROR insert into #tmp_lock_who(spid,bl) select 0 ,blocked from (select * from sysprocesses
where blocked>0 ) a where not exists(select * from (select * from sysprocesses where blocked>0 ) b where a.blocked=spid) union select spid,blocked from sysprocesses where blocked>0 IF @@ERROR<>0 RETURN @@ERROR -- 找到临时表的记录数 select @intCountProperties = Count(*),@intCounter
= 1 from #tmp_lock_who IF @@ERROR<>0 RETURN @@ERROR if @intCountProperties=0 select '现在没有阻塞和死锁信息' as message -- 循环开始 while @intCounter <= @intCountProperties begin -- 取第一条记录 select @spidspid = spid,@blbl = bl from #tmp_lock_who where Id = @intCounter begin
if @spid =0 select '引起数据库死锁的是: '+ CAST(@bl AS VARCHAR(10)) + '进程号,其执行的SQL语法如下' else select '进程号SPID:'+ CAST(@spid AS VARCHAR(10))+ '被' + '进程号SPID:'+ CAST(@bl AS VARCHAR(10)) +'阻塞,其当前进程执行的SQL语法如下' DBCC INPUTBUFFER (@bl ) end -- 循环指针下移 set @intCounter = @intCounter
+ 1 end drop table #tmp_lock_who return 0 end
游标存储过程:
sp_cursoropen cursor OUTPUT, stmt
[, scrollopt[ OUTPUT ] [ , ccopt[ OUTPUT ] [ ,rowcount OUTPUT [ ,boundparam][,...n]]] ]]
sp_cursorfetch cursor [ , fetchtype[ , rownum [ , nrows] ]]
sp_cursor cursor, optype, rownum, table [ , value[...n]]]
产生死锁的场景:
连接1:
DECLARE @cursor INT
EXEC sp_cursoropen @cursor OUTPUT, 'select * from employee', 2, 2
EXEC sp_cursorfetch @cursor, 2, 0,1
select @cursor
--返回180150003
连接2:
DECLARE @cursor INT
EXEC sp_cursoropen @cursor OUTPUT, 'select * from employee', 2, 2
EXEC sp_cursorfetch @cursor, 2, 0,1
select @cursor
现在连接2被连接1阻塞
接下来执行:
连接1:
EXEC sp_cursor 180150003, 33, 1, '', @ContactID=5 -这个语句实际上是做update
出现错误1205。
DBCC TRACEON (1222, -1) GO DBCC TRACESTATUS
DBCC TRACEOFF (1222, -1) GO DBCC TRACESTATUS
关于死锁更多信息链接:http://database.51cto.com/art/201103/247184.htm