I have a sce开发者_C百科nario here where i am running 2 separate update queries. How can I combine those into a single query by use of 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'
Q1: I think this might be the solution
ACTV_IND = MAX(CAST(ACTV_IND AS INT))
Q2: It is possible to use join for update
UPDATE T1 SET T1.C1 = :val1 FROM TABLE1 T1 join TABLE T2 ON T1.KEY1 = T2.KEY2
I would try something this like this, assuming that MAX(CAST(ACTV_IND AS INT)) will return 0 or 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
精彩评论