只是想知道,下面的代码不起作用的原因是什么?我尝试更新2个列值,如果它们符合多个条件,但我收到的错误是“' IF'和' Total'附近的语法不正确。任何帮助非常感谢!
update [dbo].[wages table]
IF([criteria1]='AA1' and [criteria2]='50yrs and below' and [criteria3]= 'X<=50')
set [Total ] = '0', [Employee ]='0' else
if ([criteria1]='AA1' and [criteria2]='50yrs and below' and [criteria3]= 'X<=50')
set [Total ] = '10', [Employee ]='10' else
if ([criteria1]='AA1' and [criteria2]='50yrs and below' and [criteria3]= 'X<=50')
set [Total ] = '20', [Employee ]='20' else
if ([criteria1]='AA1' and [criteria2]='50yrs and below' and [criteria3]= 'X<=50')
set [Total ] = '30', [Employee ]='30' else
set [Total ] = 'NULL', [Employee ]='NULL'
答案 0 :(得分:2)
在SQL
中,您可以CASE
表达此类陈述:
UPDATE [dbo].[wages table]
SET [Total] = CASE WHEN ([criteria1]='AA1' AND [criteria2]='50yrs and below' AND [criteria3]= 'X<=50') THEN '0'
WHEN ([criteria1]='AA1' AND [criteria2]='50yrs and below' AND [criteria3]= 'X<=50') THEN '0'
WHEN ([criteria1]='AA1' AND [criteria2]='50yrs and below' AND [criteria3]= 'X<=50') THEN '0'
ELSE NULL END,
[Employee ] = CASE WHEN ([criteria1]='AA1' AND [criteria2]='50yrs and below' AND [criteria3]= 'X<=50') THEN '0'
WHEN ([criteria1]='AA1' AND [criteria2]='50yrs and below' AND [criteria3]= 'X<=50') THEN '0'
WHEN ([criteria1]='AA1' AND [criteria2]='50yrs and below' AND [criteria3]= 'X<=50') THEN '0'
ELSE NULL END
此外,我不能发现你的情况有任何不同。
答案 1 :(得分:1)
我想这就是你要做的事情:
UPDATE [dbo].[wages table]
SET [Total] = CASE [criteria3] WHEN 'X<=50' THEN '0' ELSE 'NULL' END,
SET [Employee] = CASE [criteria3] WHEN = 'X<=50' THEN '0' ELSE 'NULL' END
WHERE [criteria1]='AA1' and [criteria2]='50yrs and below'
如果criteria1
和criteria2
对所有人都相同,那么您可以在WHERE
子句中查看它。我认为区别在于criteria3
。
类似的东西:
UPDATE [dbo].[wages table]
SET [Total] = CASE [criteria3] WHEN 'X<=50' THEN '0' WHEN 'X<=40' THEN 1 WHEN 'X<=30' THEN 3 ELSE 'NULL' END,
SET [Employee] = CASE [criteria3] WHEN 'X<=50' THEN '0' WHEN 'X<=40' THEN 1 WHEN 'X<=30' THEN 3 ELSE 'NULL' END
WHERE [criteria1]='AA1' and [criteria2]='50yrs and below'