我们有一个发货表,其中包含orderID(oid)和发票编号(ino)以及sequnce编号列。我正在尝试编写一个触发器,将sequnce数设置为零,或者如果存在一组唯一的oid,ino,seq,则将其递增。我不确定如何引用插入记录的OID和INO列?
这是我到目前为止所得到的:
CREATE TRIGGER SHPVIAb_insert ON [acsdcs2].[dbo].[SHPVIAb]
FOR INSERT
AS
DECLARE @newseq tinyint;
SET @newseq = 0;
IF EXISTS (SELECT *
FROM [acsdcs2].[dbo].[SHPVIAb] s
WHERE s.SHVOID_AN = inserted.SHVOID_AN
AND s.SHVINO_AN = inserted.SHVINO_AN
)
BEGIN
SET @newseq = (SELECT MAX(SHVSEQ_US)
FROM [acsdcs2].[dbo].[SHPVIAb] s
WHERE s.SHVOID_AN = inserted.SHVOID_AN
AND s.SHVINO_AN = inserted.SHVINO_AN)
SET @newseq = @newseq + 1
END
update [acsdcs2].[dbo].[SHPVIAb]
set SHVSEQ_US=@newseq;
答案 0 :(得分:0)
我认为这样的事情更接近你想要的。您想要加入到插入的表中,并处理一次插入多个记录的情况。
CREATE TRIGGER SHPVIAb_insert ON [acsdcs2].[dbo].[SHPVIAb]
FOR INSERT
AS
BEGIN
IF EXISTS ( SELECT 1
FROM [acsdcs2].[dbo].[SHPVIAb] s
INNER JOIN INSERTED i ON s.SHVOID_AN = i.SHVOID_AN
AND s.SHVINO_AN = i.SHVINO_AN )
BEGIN
UPDATE s
SET SHVSEQ_US = ( SELECT MAX(SHVSEQ_US)
FROM [acsdcs2].[dbo].[SHPVIAb] ss
WHERE ss.SHVOID_AN = s.SHVOID_AN
AND ss.SHVINO_AN = s.SHVINO_AN
) + 1
FROM [acsdcs2].[dbo].[SHPVIAb] s
INNER JOIN INSERTED i ON s.SHVOID_AN = i.SHVOID_AN
AND s.SHVINO_AN = i.SHVINO_AN
END
END