【发布时间】:2015-01-24 12:15:22
【问题描述】:
ALTER TRIGGER [dbo].[STOK_HARKETLERI_Insert]
ON [dbo].[STOK_HAREKETLERI]
FOR INSERT
AS BEGIN
declare @tip int
declare @miktar float
declare @stokkod nvarchar
declare @tarih datetime
declare @counter int
Select
@tip = sth_tip, @miktar = sth_miktar,
@stokkod = sth_stok_kod, @tarih = sth_tarih
from inserted
select @Counter = COUNT(sth_tip)
from STOK_HAREKETLERI
where sth_evraktip = 6
and sth_tip = @tip
and sth_miktar = @miktar
and @stokkod = sth_stok_kod
and @tarih = sth_tarih
if (@counter>=1)
begin
rollback
RAISERROR ('Record already exists', 17, -1) with log
end
END
GO
触发器不会在插入语句上触发,但是如果我删除变量并填充数据并在 SQL Server 上运行它,它运行良好。
有什么建议吗?
如果我将行 (@counter >= 1) 更改为 (@counter >= 0),它会再次开始工作。
【问题讨论】:
-
触发器不会为每一行执行,它是在语句级别
-
你能解释一下你的说法吗?
-
您的触发器有 MAJOR 缺陷,因为您似乎认为它会每行调用一次 - 那是不是 b> 情况。触发器将每个语句触发一次,因此如果您的
UPDATE语句影响25 行,您将触发触发器一次,然后Inserted和@987654326 @ 每个将包含 25 行。您的代码将选择这 25 行中的哪一行?它是不确定的。您需要重写触发器以考虑到这一点! -
这种事情不是最好用唯一的约束来完成吗?
-
@DavidFaber 不,为什么?因为这张表有很多类型的记录,我不想停止,我只想停止这一项。
标签: sql-server triggers insert