0

我想在触发器中动态构建一个 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)
4

1 回答 1

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;
于 2012-09-05T11:43:53.360 回答