SQL 而不是触发器有时不触发?
Table Event有一个替代触发器,其目的是生成主键EventId为Max+1,其余列由insert填充。
EventId 不是身份,我们无法使其身份,因为那里有很多依赖性,触发逻辑:
SELECT TOP 1 @ID = Event.EventID FROM Event
IF (@ID IS NULL)
BEGIN
SET @ID=1
END
ELSE
BEGIN
SELECT @ID = MAX(Event.EventID) FROM Event
SET @ID=@ID+1
END
--Then just a insert statment with this id as EventId and rest of the columns from inserted table
现在有时当我尝试插入到该表中时,它仍然说无法在 eventId 中插入重复项,不知道为什么会这样正在发生...
看起来触发器在某些情况下没有触发?为什么
Table Event has one instead of trigger, whos purpose is to generate primary key EventId as Max+1, rest of the columns are populated from inserted.
EventId is not Identity, and we can't make it identity as there is lots of depedency there, Trigger logic:
SELECT TOP 1 @ID = Event.EventID FROM Event
IF (@ID IS NULL)
BEGIN
SET @ID=1
END
ELSE
BEGIN
SELECT @ID = MAX(Event.EventID) FROM Event
SET @ID=@ID+1
END
--Then just a insert statment with this id as EventId and rest of the columns from inserted table
Now sometimes when i tries to insert into this table, it still says can't insert duplicate in eventId, Not sure why this is happning...
Looks like trigger is not fireing in some case? Why
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可能假设插入的伪表中只有一行,并且在发生多行插入时失败。
你想要这样的东西:
You're probably assuming that there's a single row in the inserted pseudo table, and failing when a multi-row insert occurs.
You want something like:
您需要使用某种锁定来防止生成重复的 ID。查看此线程类似的关于如何解决这个问题的想法的问题。
You need to use some kind of locking to prevent duplicate IDs from being generated. Take a look at this thread of a similar problem for ideas on how to tackle this.