Sql server 2008 单表上的tsql多重更新
是否有基于多个where子句更新表的方法。在一份声明中Sql server 2008 单表上的tsql多重更新,sql-server-2008,tsql,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' fro
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
有没有办法将所有这些语句合并成一个语句?是的,有:
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
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
如果列
FINAL
为INT
,则不需要用单引号将值括起来。如果这些是学生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
(我假设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.
你可以用一个案例陈述
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)
对最佳方法取决于-除了您显示的4行之外,是否还有其他行用于
Student\u ID
4行?@ypercube这是我想要举个例子的行吗?谢谢:D
尽管你的建议对这个具体案例是正确的,但整个方法都是错误的。如果一个人决定删除最后一个更新,他也会删除最后一个WHEN语句。但是WHERE子句保持不变,并且仍然匹配我们决定不更新的记录。他们的案例结果将是。。NULL@frikozoid如果他决定删除其中一个更新,他应该更新他的查询。这种方法是100%正确的。JW的工作不是计划将来对一个甚至没有提到的查询所做的更改。@JW。是的,检查结果。你能发现问题吗?@frikozoid如果是这样,那么关于这个问题的最佳更新声明是什么?