4

The following query is updating all the (80k) records instead of the ones that match (5k). What is wrong with it and how can it be corrected?

update ALAM set ALAM.CDate = (select IDCP.CDate from IDCP 
                              where ALAM.ASID = IDCP.ASID and ALAM.AID = IDCP.AID 
                                    and ALAM.MCode = '10001')

Record Count of ALAM Table = 80,000 records approx Record Count of IDCP Table = 5,000 records approx

As additional information:

select ALAM.ASID, ALAM.AID, ALAM.CDate 
from ALAM, IDCP 
where ALAM.ASID = IDCP.ASID and ALAM.AID = IDCP.AID and ALAM.MCode = '10001' 

result 5000 records approx

4 Answers 4

6
MERGE INTO ALAM
   USING IDCP 
      ON ALAM.ASID = IDCP.ASID 
         AND ALAM.AID = IDCP.AID 
         AND ALAM.MCode = '10001'
WHEN MATCHED THEN
   UPDATE 
      SET CDate = IDCP.CDate;
Sign up to request clarification or add additional context in comments.

Comments

2

You don't specify version of SQL Server. You can use the proprietary UPDATE...FROM syntax in all versions.

UPDATE ALAM
SET ALAM.CDate = IDCP.CDate
FROM ALAM
JOIN IDCP ON  ALAM.ASID = IDCP.ASID and ALAM.AID = IDCP.AID 
WHERE ALAM.MCode = '10001'

Or the more standard MERGE statement in SQL Server 2008.

Comments

1

In the first statement you haven't stated the WHERE clause on the main query. So it executes on all the records in ALAM (which I assume are 80K).

In the second query you join the 2 tables, so you only take the ones from ALAM that match the ones in IDCP. This is what went wrong.

UPDATE ALAM
SET a.CDate = i.CDate
FROM ALAM a INNER JOIN IDCP i ON a.ASID = i.ASID and a.AID = i.AID 
WHERE a.MCode = '10001'

Comments

0

As tjekkles said you left off the WHERE clause on the update which you can pull out of the inner select:

update ALAM set ALAM.CDate = (select IDCP.CDate
                                from IDCP 
                               where ALAM.ASID = IDCP.ASID
                                 and ALAM.AID  = IDCP.AID ) 
 where ALAM.MCode = '10001'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.