2011-09-01 176 views
2

我有一個場景,在這裏我運行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

Q1:我想這可能是解決

ACTV_IND = MAX(CAST(ACTV_IND AS INT)) 

Q2:可以使用加入了更新

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