插入TRIGGER以插入非零值后的SQL SERVER

时间:2018-03-26 18:02:45

标签: sql sql-server

我想在名为Client1的表上创建一个插入触发器,以将非零值插入名为Client2的表中。

例如,将以下值插入Client1表

Client_ID  CATEGORY1  CATEGORY2  CATEGORY3   CATEGORY4 CATEGORY5
 6000          1          0         1            0          0

它将触发将值插入Client2表:

INSERT INTO Client2 (Client_ID, Category_type,Value)
VALUES (6000, CATEGORY1, 1)

INSERT INTO Client2 (Client_ID, Category_type,Value)
VALUES (6000, CATEGORY3, 1)

任何人都可以帮忙吗?谢谢。

2 个答案:

答案 0 :(得分:1)

这是一种方法,它可以将您的数据转换为更有用的插入格式,然后执行此操作:

CREATE TRIGGER yourTrigger ON Client1
AFTER INSERT
AS
BEGIN
INSERT INTO Client2 (Client_ID, Category_Type, Value)
SELECT Client_ID, Category_Type, Value
FROM inserted
CROSS APPLY (VALUES (CATEGORY1,'CATEGORY1'), 
                    (CATEGORY2,'CATEGORY2'), 
                    (CATEGORY3,'CATEGORY3'), 
                    (CATEGORY4,'CATEGORY4'), 
                    (CATEGORY5,'CATEGORY5')) C (Value, Category_Type)
WHERE Value <> 0
END

您提到这是从转移表转换数据。考虑将其放入一个过程并调用它,而不是在每个插入时触发触发器。

答案 1 :(得分:1)

您可以尝试以下查询语句。

CREATE TABLE Client1 (ClintId INT, Category1 INT, Category2 INT,Category3 INT,Category4 INT,Category5 INT)

CREATE TABLE Client2(ClientId INT, CategoryType VARCHAR(100),VALUE INT)

GO
ALTER TRIGGER SampleTrigger  
ON Client1  
AFTER INSERT
AS  
    DECLARE @ClientID INT
    DECLARE @Category1 AS INT
    DECLARE @Category2 AS INT
    DECLARE @Category3 AS INT
    DECLARE @Category4 AS INT
    DECLARE @Category5 AS INT

    SELECT @ClientID = ClintId, @Category1= Category1, @Category2= Category2, 
    @Category3= Category3, @Category4 =Category4, @Category5= Category5 FROM inserted

    IF(@Category1<>0)
    BEGIN
        INSERT INTO Client2(ClientId,CategoryType,Value) VALUES(@ClientID,'Category1',@Category1)
    END
    IF(@Category2<>0)
    BEGIN
        INSERT INTO Client2(ClientId,CategoryType,Value) VALUES(@ClientID,'Category2',@Category2)
    END
    IF(@Category3<>0)
    BEGIN
        INSERT INTO Client2(ClientId,CategoryType,Value) VALUES(@ClientID,'Category3',@Category3)
    END
    IF(@Category4<>0)
    BEGIN
        INSERT INTO Client2(ClientId,CategoryType,Value) VALUES(@ClientID,'Category4',@Category4)
    END
    IF(@Category5<>0)
    BEGIN
        INSERT INTO Client2(ClientId,CategoryType,Value) VALUES(@ClientID,'Category5',@Category5)
    END

插入以下值后,您可以在Client2表上看到效果

INSERT INTO Client1(ClintId, Category1, Category2,Category3,Category4,Category5)
VALUES(6000,1,0,1,0,0)

感谢。