触发检查列值是否已更改为特定值并进行更新

时间:2017-03-14 00:35:42

标签: sql-server tsql

我想创建一个触发器来检查更改为特定值的列,并为每个值进行特定更新。如何将更改的值分配给变量并将其与if语句进行比较以进行正确的更新?现在消息显示“多部分标识符”已插入。状态“无法绑定”

    CREATE TRIGGER status_updates ON CONTACT1
    AFTER UPDATE
    AS

    DECLARE 
    @Status nvarchar(6) = inserted.Status 

    --Msg 4104, Level 16, State 1, Procedure status_updates, Line 7 [Batch Start Line 1021]
    --The multi-part identifier "inserted.Status" could not be bound.

    If @Status  = '52'
    BEGIN
        --Make Updates for code 52

    UPDATE P
    SET
         P.First_Name = T.ForeName
        ,P.Middle_Name = T.Middle_Name
        ,P.Last_name = T.Surname
    FROM SIS.dbo.People P
    INNER JOIN inserted i
        ON i.KEY4 = P.People_ID
    CROSS APPLY dbo.NameParser(i.Contact) T
    WHERE i.Key1 = '52'
    AND P.PEOPLE_ID = i.KEY4

    END

    If @Status  = '53'
    BEGIN
        --Make Updates for code 53

    UPDATE P
    SET
         P.First_Name = T.ForeName
        ,P.Middle_Name = T.Middle_Name
        ,P.Last_name = T.Surname
    FROM SIS.dbo.People P
    INNER JOIN inserted i
        ON i.KEY4 = P.People_ID
    CROSS APPLY dbo.NameParser(i.Contact) T
    WHERE i.Key1 = '53'
    AND P.PEOPLE_ID = i.KEY4

    END

    If @Status  = '54'
    BEGIN
        --Make Updates for code 54

    UPDATE P
    SET
         P.First_Name = T.ForeName
        ,P.Middle_Name = T.Middle_Name
        ,P.Last_name = T.Surname
    FROM SIS.dbo.People P
    INNER JOIN inserted i
        ON i.KEY4 = P.People_ID
    CROSS APPLY dbo.NameParser(i.Contact) T
    WHERE i.Key1 = '55'
    AND P.PEOPLE_ID = i.KEY4;

    END

    If @Status  = '55'
    BEGIN
        --Make Updates for code 55

INSERT INTO SIS.dbo.People (First_Name,Middle_Name,Last_Name)
SELECT
     T.ForeName
    ,T.Middle_Name
    ,T.Surname
FROM inserted i --change to inserted
INNER JOIN SIS.dbo.People P
    ON P.People_ID = i.Key4
CROSS APPLY dbo.NameParser(i.Contact) T
WHERE i.Key1 = '55'

    END

    GO

1 个答案:

答案 0 :(得分:1)

我认为你正在寻找这样的东西:

CREATE TRIGGER status_updates ON CONTACT1
AFTER UPDATE
AS
    UPDATE P
    SET
         P.First_Name = T.ForeName
        ,P.Middle_Name = T.Middle_Name
        ,P.Last_name = T.Surname
    FROM SIS.dbo.People P
    INNER JOIN inserted i
        ON i.KEY4 = P.People_ID
    CROSS APPLY dbo.NameParser(i.Contact) T
    WHERE (i.Key1 = '52' AND i.[Status] = '52')
    OR (i.Key1 = '53' AND i.[Status] = '53')
    OR (i.Key1 = '54' AND i.[Status] = '54') 

    INSERT INTO SIS.dbo.People (First_Name,Middle_Name,Last_Name)
    SELECT
         T.ForeName
        ,T.Middle_Name
        ,T.Surname
    FROM inserted i --change to inserted
    INNER JOIN SIS.dbo.People P
        ON P.People_ID = i.Key4
    CROSS APPLY dbo.NameParser(i.Contact) T
    WHERE i.Key1 = '55'
    AND i.Status = '55'
GO