有个表就table1吧
id haoma date
其中id是自增列的主键 ,haoma是个varchar值,date是个时间不带小时分钟的,比如 2010-10-10 ,默认是当天。
现在要求在当天不能插入二个相同的haoma。不是当天的就无所谓了
我是这样弄的
select count(haoma) from table1 where haoma=@haoma and date=今天
如果count为0,就插入,不为0就弹出提示。单发现查询死锁现象非常严重,很容易数据库就卡死了(大约有100个客户端)
于是我就新加个表table2,记录一下今天插入的haoma,然后做个操作作业凌晨时候把表清空(凌晨的时候客户端没有操作的了)
也是 select count(haoma) from table2 where haoma=@haoma 这样做发现死锁现象依然经常发生,只不过比上一个频率少了点。
------解决思路----------------------
if exists(select * from table1 where haoma=@haoma and [date]=cast(getdate() AS date))
begin
--执行插入操作
end
------解决思路----------------------
直接这样写
insert into table1(haoma,date)
select haoma='TestHaoma',date = '今天'
where not exists (
select 1 from table1
where haoma='TestHaoma' and date = '今天'
)
------解决思路----------------------
table1表在 haoma + date 加个索引
------解决思路----------------------
你插就让别人随便插,然后弄个job每天凌晨的时候清除掉你不要的数据,批量删除,这样就不会有死锁了,否则你每次都判断,对数据库性能本身就是一个噩耗