We help IT Professionals succeed at work.

SQL UPDATE QUERY PROBLEM

DaveChoiceTech
on
This is my problem

Table A has columns ID1,ID2 and NAME
Table B has columns ID1 and CATEGORY
Table C has columns ID1, ID2

B.CATEGORY can have the value X,Y and Z
A.ID2 has not had any values assigned

Step A: Get C.ID1, C.ID2 where C.ID1=B.ID1 and B.CATEGORY = 'X'
Step B: Update A.ID2 with C.ID2 where C.ID1 = A.ID1 for the records selected in step A

I am using DB2
Comment
Watch Question

Dave FordSoftware Developer / Database Administrator

Commented:
This should get you close. I split it into two steps for clarity.

create table StepA as (
   select c.ID1, c.ID2
     from TableC c
     join TableB b
       on b.id1 = c.id1
      and b.category = 'X'
) with data

Open in new window


Step B: Update A.ID2 with C.ID2 where C.ID1 = A.ID1 for the records selected in step A

update TableA a
   set a.id2 = (
       select id2
         from StepA s
        where s.id1 = a.id1)
 where exists (select 1
                 from StepA sa
                where sa.id1 = a.id1
                  and sa.id2 = a.id2)

Open in new window


HTH,
DaveSlash

Author

Commented:
I need to do this without creating an intermediate table.
Data Warehouse / Database Architect
Commented:
Hi Dave,

The UPDATE statement varies quite a bit between DB2, Oracle, and SQL Server.  If you're used to another platform you'll need to add the DB2 format to your arsenal.

But you should be able to do this with the MERGE statement on any platform.

MERGE INTO A
USING
(
    SELECT C.ID1, C.ID2
    FROM C
    INNER JOIN B
      ON B.ID1= C.ID1
     AND B.CATEGORY = "X'
) t0
  ON A.ID1 = t0.ID1
WHEN MATCHED THEN
  UPDATE SET A.ID2 = C.ID2

Open in new window


I think that will work for you.

Good Luck!
Kent

Author

Commented:
Perfect!