在INSERT触发器中动态构建UPDATE语句

时间:2012-09-05 11:32:07

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

我想在触发器中动态构建UPDATE语句,因此我需要一些关于临时变量和长度相关函数的帮助,并使用临时变量来指定UPDATE语句中的字段/更新值:

stSQL as string
stSQL = ""

IF FieldA=<criteria> then
 stSQL = "FieldB = we_ci_db.dbo.ztblTest.FieldA"
endif

IF FieldG=<criteria> then
 if len(stSQL)>0 then stSQL=stSQL & " AND "
 stSQL = "FieldH = we_ci_db.dbo.ztblTest.FieldF"
else
 if len(stSQL)>0 then stSQL=stSQL & " AND "
 stSQL = "FieldH = we_ci_db.dbo.ztblTest.FieldG"
endif

UPDATE ztblTest
SET stSQL
WHERE TestID IN (SELECT DISTINCT TestID FROM inserted)

1 个答案:

答案 0 :(得分:2)

在我看来,您不需要构建字符串,使用动态SQL或拥有所有这些IF条件。两个简单的内联CASE表达式似乎就是这样做的:

UPDATE z
SET FieldB = CASE WHEN i.FieldA = <criteria> THEN i.FieldA ELSE i.FieldB END,
    FieldH = CASE WHEN i.FieldG = <criteria> THEN i.FieldF ELSE i.FieldG END
FROM dbo.ztblTest AS z
INNER JOIN inserted AS i
ON z.TestID = i.TestID;