我的应用程序在处理过程中需要在某一瞬间对某表进行锁定,
若进程正常运行的话,是会自动解锁的,
但现在进程在解锁前意外结束,导致之后的一些操作无法进行!
问:
1、在数据库中有没有办法设定一个监视:
当我的锁在一段时间后仍未解锁,通过调用SQL脚本将锁解掉?
2、锁的一些信息,如被锁的对像、锁的时间等是放在哪个表里的?
火烧睫毛,搞不掂俺今年春节就休想回家过年了,请高手踊跃献策!
--设tb(A,B,C)
create table #tb(A varchar(2),B varchar(2),C varchar(2))
insert into #tb
select a1,b1,c1
union all select a2,b2,c2
union all select a3,b3,c3
--1)排它锁
--在第一个连接中执行以下语句
begin tran
update #tb
set A=aa
where B=b2
waitfor delay 00:00:3 --等待3秒
commit tran
--在第二个连接中执行以下语句
begin tran
select * from #tb
where B=b2
commit tran
--若同时执行上述两个语句,则select查询必须等待update执行完毕才能执行即要等待30秒
--2)共享锁
--在第一个连接中执行以下语句
begin tran
select * from #tb holdlock --holdlock人为加锁
where B=b2
waitfor delay 00:00:3 --等待3秒
commit tran
--在第二个连接中执行以下语句
begin tran
select A,C from #tb
where B=b2
update #tb
set A=aa
where B=b2
commit tran
--若同时执行上述两个语句,则第二个连接中的select查询可以执行
--而update必须等待第一个连接中的共享锁结束后才能执行 即要等待30秒
--3)死锁
--增设tb2(D,E)
create table #tb2(D varchar(2),E varchar(2))
insert into #tb2
select d1,e1
union all select d2,e2
--在第一个连接中执行以下语句
begin tran
update #tb
set A=aa
where B=b2
waitfor delay 00:00:5
update #tb2
set D=d5
where E=e1
commit tran
--在第二个连接中执行以下语句
begin tran
update #tb2
set D=d5
where E=e1
waitfor delay 00:00:3
update #tb
set A=aa
where B=b2
commit tran
--删除临时表
drop table #tb,#tb2
--同时执行,系统会检测出死锁,并中止进程
/*-------------------------------------------------------------
SET IMPLICIT_TRANSACTIONS ON --用户每次必须显式提交或回滚。否则当用户断开连接时,
--事务及其所包含的所有数据更改将回滚
SET IMPLICIT_TRANSACTIONS OFF --自动提交模式。在自动提交模式下,如果各个语句成功
--完成则提交。
------------------------------------------------------------------------*/
Set Lock_TimeOut 是不是设置整个数据库的锁超时?
--------------
是
不知道这样行不行?
写一个存储过程来kill锁进程。 用job定时调用此存储过程来kill
1:
create proc killspid (@dbname varchar(20))
as
begin
declare @sql nvarchar(500),@temp varchar(1000)
declare @spid int
set @sql=declare getspid cursor for
select spid from sysprocesses where blocked <>0 and dbid=db_id(+@dbname+)
exec (@sql)
open getspid
fetch next from getspid into @spid
while @@fetch_status =0
begin
set @temp=kill +rtrim(@spid)
exec(@temp)
fetch next from getspid into @spid
end
close getspid
deallocate getspid
end
2:
用JOB调度。
你的数据库服务器-》企业管理器-》管理-》SQL Server 代理-》作业-》新建作业,按照要求填就可以了,在“步骤”的“命令”中填写你要执行的存储过程或语句,在“调度”里面填写什么时间执行
EXEC sp_add_job @job_name = 作业名字
EXEC sp_add_jobstep @job_name = 作业名字,
@step_name = 步骤名子,
@subsystem = TSQL,
@command = EXEC 库名..过程名,
@retry_attempts = 5, --重试次数
@retry_interval = 5 --重试间隔
EXEC sp_add_jobschedule @job_name = 作业名字,
@name = 作业调度名字,
@freq_type = 4, -- 每天
@freq_interval = 26, --间隔
@active_start_time = 10000 --开始时间