码迷,mamicode.com
首页 > 数据库 > 详细

SQL server下死锁问题

时间:2014-08-06 10:24:41      阅读:255      评论:0      收藏:0      [点我收藏+]

标签:style   color   使用   io   数据   问题   ar   cti   

这几天在做一个项目,以前都没怎么搞过多线程,现在开始,只有边学边做了。

一开始的时候,程序报错是,是提示发生死锁,刚开始,自己没什么经验,以为是程序代码的死锁,就用lock代码,把程序给锁起来了,运行程序后,发现有超时现象,查阅资料,后来断定,这个问题是死锁是发生是SQL server上的,特地找了下SQL2008的书,看了下,死锁的解释。

 

共享锁

排他锁 

更新锁

自定义锁

 

然后查了资料,
查询SQL死锁的 存储过程
 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 sys.sysprocesses where blocked>0 ) a
   where not exists(select * from (select * from sys.sysprocesses where blocked>0 ) b
   where a.blocked=spid)
   union select spid,blocked from sys.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 @spid = spid,@bl = 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
 
分析了一下
通过自定义锁 WIHT NOLOCK(注意有脏读,请根据业务逻辑使用)with rowlock来使用的时候,解决了一部分死锁的,但是还是会发生死锁的现象
查找了代码,发现主要出的问题是在一些begin tran的事务上面
因为在事务里面使用delete和update命令的时候,还没有执行commit或则rollback,如果另一个线程同样在执行当前的表DELETE命令的时候,会出现阻塞的现象,阻塞是造成死锁的前提,oracle好像没有这个问题,oracle是锁行的,这个时候,我根据SQL的命令,将UPDATE后面的条件的字段,在数据库建立索引,如 delete from table where b=3
将字段b建立索引,就会自动将锁表变成锁行,注意如果索引建立的是B字段,而你条件是C字段,则不会发生锁行效果
 

SQL server下死锁问题,布布扣,bubuko.com

SQL server下死锁问题

标签:style   color   使用   io   数据   问题   ar   cti   

原文地址:http://www.cnblogs.com/yangweicheng/p/3893861.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!