Re: help with an update statement using with and "(values" -
01-07-2012
, 07:45 PM
score_no would be set to null in my last example, if the row in a
doesn't match with b.
To keep values of score_no at the time the row doesn't match with b.
UPDATE scores a
SET score_no
= COALESCE(
(SELECT b.score_no
FROM (VALUES (201101954 , 3 , 1 , 0.20)
, (201101954 , 3 , 4 , 0.20)
, (201101954 , 3 , 5 , 0.10)
, (201101954 , 3 , 6 , 0.05)
, (201101954 , 3 , 7 , 0.07)
, (201101954 , 3 , 8 , 0.09)
) b(p_id , r_id , z_id , score_no)
WHERE a.p_id = b.p_id
AND a.r_id = b.r_id
AND a.z_id = b.z_id
)
, a.score_no
)
;
Or, it would be better to use a MERGE statement.
MERGE scores a
USING (VALUES (201101954 , 3 , 1 , 0.20)
, (201101954 , 3 , 4 , 0.20)
, (201101954 , 3 , 5 , 0.10)
, (201101954 , 3 , 6 , 0.05)
, (201101954 , 3 , 7 , 0.07)
, (201101954 , 3 , 8 , 0.09)
) b(p_id , r_id , z_id , score_no)
ON b.p_id = a.p_id
AND b.r_id = a.r_id
AND b.z_id = a.z_id
WHEN MATCHED THEN
UPDATE
SET score_no = b.score_no
; |