对触发器中的所有插入值求和

时间:2016-08-25 14:46:21

标签: sql sql-server triggers sql-server-2008-r2

假设我有下表T1

| type | col1 | col2 |
|------|------|------|
| abc  | 0    | 0    |
| def  | 0    | 3    |
| abc  | 3    | 123  |
| def  | 0    | 5    |
| def  | 2    | 4    |

定期将一些新值插入T1。我现在想要创建一个触发器,它会填充另一个表T2,具体取决于插入T1的值。

可以使用以下伪代码计算要插入T2的值:

IF col1 = 0 AND col2 = 0
    A++
ELSE IF col1 = 0 col2 > 0
    B++
ELSE IF col1 > 0
    C++

我已经创建了以下触发器:

Create TRIGGER TRI1
    ON dbo.T1
    FOR INSERT
AS
BEGIN
  INSERT INTO dbo.T2
    SELECT Sum(CASE WHEN col1 = 0 AND col2 = 0 THEN 1 END) as 'A',
           Sum(CASE WHEN col1 = 0 AND col2 > 0 THEN 1 END) as 'B',
           Sum(CASE WHEN col1 > 0 THEN 1 END) as 'C'
    FROM INSERTED 
END

当我用以下方法测试时:

INSERT INTO dbo.T1 VALUES ('abc',2,3)
INSERT INTO dbo.T1 VALUES ('abc',0,0)
INSERT INTO dbo.T1 VALUES ('def',0,3)
INSERT INTO dbo.T1 VALUES ('abc',0,0)

我得到以下输出:

| A    | B    | C    |
|------|------|------|
| NULL | NULL | 1    |
| 1    | NULL | NULL |
| NULL | 1    | NULL |
| 1    | NULL | NULL |

但是每个插入操作的预期输出只有1行:

| A | B | C |
|---|---|---|
| 2 | 1 | 1 |

1 个答案:

答案 0 :(得分:1)

您应该创建一个这样的触发器,

CREATE TRIGGER TRI1 ON dbo.T1
FOR INSERT
AS
BEGIN
    IF EXISTS (
            SELECT 1
            FROM dbo.T2
            )
    BEGIN
        UPDATE T
        SET A = Sum(CASE 
                    WHEN T.col1 = 0
                        AND T.col2 = 0
                        THEN 1
                    ELSE 0
                    END)
            ,B = Sum(CASE 
                    WHEN T.col1 = 0
                        AND T.col2 > 0
                        THEN 1
                    ELSE 0
                    END)
            ,C = Sum(CASE 
                    WHEN T.col1 > 0
                        THEN 1
                    ELSE 0
                    END)
        FROM dbo.t1 T
    END
    ELSE
    BEGIN
        INSERT INTO dbo.T2
        SELECT Sum(CASE 
                    WHEN T.col1 = 0
                        AND T.col2 = 0
                        THEN 1
                    ELSE 0
                    END) AS 'A'
            ,Sum(CASE 
                    WHEN T.col1 = 0
                        AND T.col2 > 0
                        THEN 1
                    ELSE 0
                    END) AS 'B'
            ,Sum(CASE 
                    WHEN T.col1 > 0
                        THEN 1
                    ELSE 0
                    END) AS 'C'
        FROM dbo.t1 T
    END
END