1

I have a trigger which inserts data to a table from another table based on a condition like below :

DECLARE @pID VARCHAR(50);

SELECT @pID = I.pID FROM inserted I;

INSERT  INTO Queue ( ID )
        SELECT  ID
        FROM    Inventory
        WHERE   pID = @pID

How can I check if the ID exist before inserting?

Note : There will be multiple records returned from -

SELECT  ID
            FROM    Inventory
            WHERE   pID = @pID
4

1 回答 1

1

正如您已经提到的,[inserted] 可以包含零个、一个或多个记录。将该信息存储到变量中的方法将不起作用。

无论如何,我假设您要检查是否存在以避免在 Queue table 中多次输入相同的 ID?

在这种情况下,您可以在触发器中使用以下代码:

INSERT  INTO Queue ( ID )
        SELECT  DISTINCT I.ID -- as to avoid same ID being inserted multiple times
        FROM    Inventory I
        JOIN    inserted
          ON    inserted.pID = I.pID
        WHERE   NOT EXISTS ( SELECT *
                               FROM Queue Q
                              WHERE Q.ID = I.ID )
于 2013-09-30T11:07:50.247 回答