Sql server 2008 如何基于不同的where子句在SQL中进行更新
我有一张表,其结构如下:Sql server 2008 如何基于不同的where子句在SQL中进行更新,sql-server-2008,sql-update,Sql Server 2008,Sql Update,我有一张表,其结构如下: ID DBInstance DBName Tag 1 | INS1 | master | NULL 2 | INS1 | tempdb | NULL 4 | INS2 | master | NULL 5 | INS2 | tempdb | NULL 我想根据以下条件更新此表中的标记: 1) 仅将DBInstance的标记更新为“a”,将DBName的标记更新为“INS1”,将DBName的标记更新为“master” 2)
ID DBInstance DBName Tag
1 | INS1 | master | NULL
2 | INS1 | tempdb | NULL
4 | INS2 | master | NULL
5 | INS2 | tempdb | NULL
我想根据以下条件更新此表中的标记:
1) 仅将DBInstance的标记更新为“a”,将DBName的标记更新为“INS1”,将DBName的标记更新为“master”
2) 仅将DBInstance的标记更新为“b”,将DBName的标记更新为“INS2”,将DBName的标记更新为“tempdb”
我只想在一条语句中更新这两条语句,而不是在两个不同的更新查询中。我怎样才能做到?
类似这样的查询:
UPDATE tbl_test
SET tag = 'a' where DBInstance in ('INS1') and DBName IN ('master'),
tag = 'b' where DBInstance in ('INS2') and DBName IN ('tempdb')
UPDATE tbl_test
SET tag = case
when DBInstance = 'INS1' and DBName = 'master'
then 'a'
when DBInstance = 'INS2' and DBName = 'tempdb'
then 'b'
else NULL -- or may be tag, or default value which you want.
end
但是很明显,这个查询是错误的,那么我该怎么做呢?您可以使用
案例,然后像这样:
UPDATE tbl_test
SET tag = 'a' where DBInstance in ('INS1') and DBName IN ('master'),
tag = 'b' where DBInstance in ('INS2') and DBName IN ('tempdb')
UPDATE tbl_test
SET tag = case
when DBInstance = 'INS1' and DBName = 'master'
then 'a'
when DBInstance = 'INS2' and DBName = 'tempdb'
then 'b'
else NULL -- or may be tag, or default value which you want.
end
@Tony可能是对的,只是用例语句,比如,set tag CASE WHEN…..END
@rahultripati-是的,我删除了我的评论,因为我意识到它们已经为空了。。。但我想我还是要提一下,以防有人在没有意识到的情况下删除了值