单个表上的s sql多次更新

时间:2013-03-08 14:40:01

标签: sql-server-2008 tsql

有没有办法根据多个where子句更新表。在一个单一的声明中?

update A
set Final = '21'
from StudentTable A
where Student_ID= 4 and bitcm= 0 and receipt= 17



update B
set Final = '22'
from StudentTable B
where Student_ID=4 and bitcm= 0 and receipt =12


update C
set Final ='11'
from StudentTable C
where Student_ID=4 and bitcmp=1 and receipt=17


update D
set Final ='12'
from StudentTable D
where Student_ID=4 and bitcmp=1 and receipt=12

有没有办法将所有这些语句合并为一个语句?

3 个答案:

答案 0 :(得分:4)

是的,有:

UPDATE  A
SET     Final = CASE WHEN bitchcm = 0 AND receipt = 17 THEN '21'
                     WHEN bitchcm = 0 AND receipt = 12 THEN '22'
                     WHEN bitchcm = 1 AND receipt = 17 THEN '11'
                     WHEN bitchcm = 1 AND receipt = 12 THEN '12'
                END
FROM    StudentTable A
WHERE   Student_ID = 4 AND   -- the purpose of the three conditions
        bitcm IN (0,1) AND   -- is to speed up the query. It will not
        receipt IN (12,17)   -- scan the whole records on the table

如果列FINALINT,那么您不需要用单引号包装值。

答案 1 :(得分:3)

如果这些是Student_ID 4的唯一四行,那么以下工作:

update A
set Final = CASE
    WHEN bitcm=0 and receipt=17 THEN '21'
    WHEN bitcm= 0 and receipt =12 THEN '22'
    WHEN bitcmp=1 and receipt=17 THEN '11'
    WHEN bitcmp=1 and receipt=12 THEN '12'
    END
from StudentTable A
where Student_ID= 4

(我认为bitcmbitcmp应该是同一列,但我不确定要使用哪种拼写

更通用的方法是使用包含所有必需键列和新Final值的表(可能是表变量或参数)。然后你会写:

UPDATE A
SET Final = B.Final
FROM StudentTable A
INNER JOIN @AboveMentionedTableVariableOrParameter B
ON
    A.Student_ID = B.Student_ID and
    A.bitcm = b.bitcm and
    A.receipt = b.receipt --And add any other necessary conditions here.

答案 2 :(得分:1)

您可以使用CASE声明

UPDATE StudentTable
SET Final = 
 CASE WHEN Student_ID= 4 and bitcm= 0 and receipt= 17 THEN 21
  WHEN Student_ID=4 and bitcm= 0 and receipt =12 THEN 22
  WHEN Student_ID=4 and bitcmp=1 and receipt=17 THEN 11
  WHEN Student_ID=4 and bitcmp=1 and receipt=12 THEN 12
 END
WHERE Student_ID = 4
AND bitcm IN (0,1)
AND receipt IN (12,17)