SQL Server触发案例语句未捕获

时间:2019-05-30 00:05:26

标签: sql sql-server ssms

我试图创建一个触发器,当SAMPLE表列更新时,它使用case语句更新另一个表中的列。当前,触发器不捕获任何WHEN子句。 ELSE子句中的值是用于执行更新的内容。

CREATE TRIGGER dbo.SAMPVAL
ON dbo.SAMPLE
FOR UPDATE
AS
BEGIN
    UPDATE U
    SET U.VALIDATED = CASE
                         WHEN (U.VALIDATED IS NULL AND LEN(INSERTED.VALUSER) > 0)  
                            THEN 'VAL1'
                         WHEN (LEN(U.VALIDATED) > 0 AND U.VALIDATED = 'VAL1') 
                            THEN 'VAL2'
                         WHEN (LEN(U.VALIDATED) = 0) 
                            THEN 'NEWERVAL'
                         WHEN (LEN(U.VALIDATED) > 0) 
                            THEN 'NEWERVAL1'
                         ELSE '-'
                      END
    FROM INSERTED 
    INNER JOIN SUSERFLDS U ON U.SAMPNO = INSERTED.SAMPNO
END;

如果U.VALIDATED字段为空,并且SAMPLE.VALUSER列的长度大于零,则SUSERFLDS.VALIDATED = 'VAL1'。当我对此进行测试时,SUSERFLDS.VALIDATED列将更新为“-”。

1 个答案:

答案 0 :(得分:0)

CREATE TRIGGER dbo.SAMPVAL
ON dbo.SAMPLE
FOR UPDATE
AS BEGIN
  UPDATE U
    SET U.VALIDATED = CASE
    WHEN (U.VALIDATED IS NULL AND LEN(INSERTED.VALUSER) > 0) THEN 'VAL1'
    WHEN (LEN(U.VALIDATED) > 0 AND U.VALIDATED = 'VAL1') THEN 'VAL2'
    WHEN (LEN(U.VALIDATED) = 0) THEN 'NEWERVAL'
    WHEN (LEN(U.VALIDATED) > 0) THEN 'NEWERVAL1'
    ELSE U.VALIDATED
    END
  FROM INSERTED 
  INNER JOIN SUSERFLDS U ON U.SAMPNO =INSERTED.SAMPNO
END;

ELSE '-'更改为ELSE U.VALIDATED可以解决此问题。