How to increment a specific column based on the value in another column in the same table

时间:2015-06-25 18:41:53

标签: sql triggers sql-server-2014

I have a table that I will be using for a tally. Within that table I have the following columns: T_ID, L_ID,L1,L2,L3,L4,L5. L_ID is of the data type INT. The value in L_ID can go up to 5. I want to create a trigger that checks the value in L_ID, depending on that value whether it be from 1 to 5. It will increment the corresponding column L1,L2,L3,L4,L5, these values are automatically zero. For example L_ID=3 therefore L3 will increment by one.

1 个答案:

答案 0 :(得分:0)

因此,您可以使用case表达式而不是插入/更新触发器,而不是原始插入的插入(假设您希望在原始插入上执行此行为而不是仅在0处的所有Lx列:

CREATE TRIGGER [dbo].[InsteadTrigger] ON [dbo].[original_table]
    INSTEAD OF INSERT
AS
    INSERT  INTO original_table
            SELECT  L_ID ,
                    CASE WHEN L_ID = 1 THEN L1 + 1
                         ELSE L1
                    END ,
                    CASE WHEN L_ID = 2 THEN L2 + 1
                         ELSE L2
                    END ,
                    CASE WHEN L_ID = 3 THEN L3 + 1
                         ELSE L3
                    END ,
                    CASE WHEN L_ID = 4 THEN L4 + 1
                         ELSE L4
                    END ,
                    CASE WHEN L_ID = 5 THEN L5 + 1
                         ELSE L5
                    END
            FROM    INSERTED;
        GO 

然后,要获得更新工作,您需要一个而不是更新触发器,例如:

CREATE TRIGGER InsteadUpdTrigger ON original_table
    INSTEAD OF UPDATE
AS
    UPDATE  original_table
    SET     L_ID = i.L_ID ,
            L1 = CASE WHEN i.L_ID = 1 THEN i.L1 + 1
                      ELSE i.L1
                 END ,
            L2 = CASE WHEN i.L_ID = 2 THEN i.L2 + 1
                      ELSE i.L2
                 END ,
            L3 = CASE WHEN i.L_ID = 3 THEN i.L3 + 1
                      ELSE i.L3
                 END ,
            L4 = CASE WHEN i.L_ID = 4 THEN i.L4 + 1
                      ELSE i.L4
                 END ,
            L5 = CASE WHEN i.L_ID = 5 THEN i.L5 + 1
                      ELSE i.L5
                 END
    FROM    INSERTED i
    WHERE   original_table.T_ID = i.T_ID;

请注意,我已假设此处的T_ID是主键,在此情况下需要确保更新触发器仅修改原始更新中涉及的行。