我有一个(希望)快速的SQL问题让我疯狂,我无法在任何地方找到答案。
我有以下SQL触发器:
DECLARE @ABCOwnerGroup varchar(30)
DECLARE @DEFOwnerGroup varchar(30)
SET @ABCOwnerGroup='GROUP ONE'
SET @DEFOwnerGroup='GROUP TWO'
etc..
--IF OWNERGROUP IS MISSING (Location NOT NULL)
UPDATE wo
SET wo.ownergroup='@'+SUBSTRING(wo.location,1,3)+'OwnerGroup'
FROM dbo.workorder AS wo INNER JOIN inserted AS i ON wo.wonum=i.wonum
WHERE wo.status<>'COMP'
AND wo.historyflag=0
AND wo.istask=0
AND wo.ownergroup IS NULL
AND wo.location IS NOT NULL
有关您的信息,位置代码类似于“ABC-12345”,其中ABC基本上是网站,12345是建筑物。所以SUBSTRING(wo.location,1,3)拉出了该位置的ABC部分,以便它可以填入@ABCOwnerGroup
问题是它插入了值'@ABCOwnerGroup'而不是'GROUP ONE'
非常感谢任何和所有帮助!希望这是一个小错误!
答案 0 :(得分:4)
或者,如果没有动态sql,您可以获得相同的结果:
--IF OWNERGROUP IS MISSING (Location NOT NULL)
UPDATE wo
SET wo.ownergroup = CASE SUBSTRING(wo.location, 1, 3)
WHEN 'ABC' THEN 'GROUP ONE'
WHEN 'DEF' THEN 'GROUP TWO'
END
FROM dbo.workorder AS wo
INNER JOIN inserted AS i ON wo.wonum = i.wonum
WHERE wo.status <> 'COMP'
AND wo.historyflag = 0
AND wo.istask = 0
AND wo.ownergroup IS NULL
AND wo.location IS NOT NULL
答案 1 :(得分:3)
您需要使用EXECUTE来执行动态SQL
EXEC('UPDATE wo SET wo.ownergroup=@'+SUBSTRING(wo.location,1,3)+'OwnerGroup FROM dbo.workorder AS wo INNER JOIN inserted AS i ON wo.wonum=i.wonum
WHERE wo.status<>''COMP''
AND wo.historyflag=0
AND wo.istask=0
AND wo.ownergroup IS NULL
AND wo.location IS NOT NULL')
答案 2 :(得分:2)
您需要将整个更新表示为字符串,并使用Exec执行它。