更新中的CASE语句

时间:2011-09-01 23:25:04

标签: sql sql-server sql-server-2008

我在这里有一个场景,我正在运行2个单独的更新查询。 如何通过使用case将它们组合成单个查询?

UPDATE TABLE1 SET ACTV_IND = 0
WHERE NAME IN (
  select NAME
  from TABLE1
  where SID = 'child'
  group by NAME
  having MAX(CAST(ACTV_IND AS INT)) =0
)
AND SID = 'parent'
UPDATE TABLE1 SET ACTV_IND = 1
WHERE NAME IN (
  select NAME
  from TABLE1
  where SID = 'child'
  group by NAME
  having MAX(CAST(ACTV_IND AS INT)) =1
)
AND SID = 'parent'

1 个答案:

答案 0 :(得分:1)

Q1:我认为这可能是解决方案

  ACTV_IND =  MAX(CAST(ACTV_IND AS INT)) 

Q2:可以使用join for update

UPDATE T1 SET T1.C1 = :val1 FROM TABLE1 T1 join TABLE T2 ON T1.KEY1 = T2.KEY2

我会尝试这样的事情,假设MAX(CAST(ACTV_IND AS INT))将返回0或1

WITH DATA_SOURCE (NAME, VAL) AS (
 select NAME, MAX(CAST(ACTV_IND AS INT)) VAL from TABLE1 where SID = 'child' group by NAME
)
UPDATE TABLE1
 SET ACTV_IND  = DS.VAL 
FROM TABLE1 T1 JOIN DATA_SOURCE DS ON T1.NAME = DS.NAME
WHERE T1.SID = 'parent'
GO