2

有没有办法根据多个 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

有没有办法将所有这些语句组合成一个语句?

4

3 回答 3

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

如果 columnFINAL是,INT那么您不需要用单引号将值括起来。

于 2013-03-08T14:42:40.337 回答
3

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

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

(我假设bitcm并且bitcmp应该是同一列,但我不确定使用哪个拼写)

更通用的方法是创建一个表(可能是表变量或参数),其中包含所有必需的键列和新的最终值。然后你会写:

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.
于 2013-03-08T14:43:55.447 回答
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) 
于 2013-03-08T14:44:15.357 回答