我编写了以下 SQL 来更新表值:
Update Table
SET S_Type = 'Versus'
Where S_Type = 'REGULAR'
SET S_Type = 'Free'
Where S_Type = 'CASH';
我的 SQL 相当生疏,我的同事告诉我它出了点问题,但没有告诉我是什么!
唯一想到的是我没有提到 set 和 Where 代码中的 Table.Column。
像这样更新列有什么问题吗?为多个值更新列时的最佳做法是什么?
干杯
我编写了以下 SQL 来更新表值:
Update Table
SET S_Type = 'Versus'
Where S_Type = 'REGULAR'
SET S_Type = 'Free'
Where S_Type = 'CASH';
我的 SQL 相当生疏,我的同事告诉我它出了点问题,但没有告诉我是什么!
唯一想到的是我没有提到 set 和 Where 代码中的 Table.Column。
像这样更新列有什么问题吗?为多个值更新列时的最佳做法是什么?
干杯
在这里,我们使用 case 语句并找到类似 where 子句的结果:
update tablename
set S_Type = (case S_Type when 'REGULAR' then 'Versus'
when 'CASH' then 'free'
else s_type
end)
Update YourTable
set S_Type =
case S_Type
when 'REGULAR' then 'Versus'
when 'CASH' then 'free'
else s_type
end
你在使用 SQL Server 吗?如果您使用的是 2012,您现在可以使用新的 CHOOSE 或 IIF 功能编写简化的条件更新语句,例如:
Update YourTable
set S_Type = IIF(S_Type = 'REGULAR', 'Versus', 'free')
我的两便士值。