SQL UPDATE QUERY PROBLEM

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
DaveChoiceTechAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Dave FordSoftware Developer / Database AdministratorCommented:
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
0
DaveChoiceTechAuthor Commented:
I need to do this without creating an intermediate table.
0
Kent OlsenDBACommented:
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
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
DaveChoiceTechAuthor Commented:
Perfect!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
DB2

From novice to tech pro — start learning today.