0

I want to update the table IVRecords set IVNO = value return by a subquery

While (Select Count(*) From [IVRecords] Where IVNO= '22644') > 0
Begin

    update [IVRecords] set IVNO= (Select  a.IVNO from [DVHead] a  inner join [IVRecords] b on a.DELIVERYNO=b.DELIVERYNO)

End

But the subquery return multiple value : 254,325,25346,25346 I have over 58000 records

So how to update the table IVRecords with the value return by subquery Select a.IVNO from [DVHead] a inner join [IVRecords] b on a.DELIVERYNO=b.DELIVERYNO) one by one?

The IVNo of IVRecords has the duplicated value 22644 caused by making mistake updation. And the IVNO of DVHead is the right IVNO of IVRecords. So I want to copy them to the IVRecords that has the wrong IVNo. 02 tables have key DELIVERYNO. My expected result: Before:

IVRecord     
DELIVERYNO   IVNO 
253           22664
253          22664
456          22664
789          22664

DVHead
DELIVERYNO   IVNO
253          1234
456          5236
789           6478
Expected result

IVRecord     
DELIVERYNO   IVNO 
253           1234
253          1234
456          5236
789          6478

2
  • What are you actually trying to do here? Commented Apr 24, 2018 at 8:50
  • please see my edited post Commented Apr 24, 2018 at 9:05

1 Answer 1

2

I think this would be an equivalent set-based version of your code:

update ivr
    set ivr.ivno = a.ivno
from IVRecords ivr
    inner join DVHead a
        on ivr.deliveryNO = a.deliveryno
where ivr.ivno = '22664'

This should run much faster than the row-by-row (one by one) version in your question.

Also, here's a SQLFiddle with how the code works.

(Although, if something's not right, please post an example of what data you have and the expected output)

Sign up to request clarification or add additional context in comments.

7 Comments

Is it really? To me it looks like he/she wants to update the IVRecords table as long as there is a invo= 22264 record in the table. Confusing indeed...
@user3035133 Then please post an example of what data you have now and what is the expected output.
@user3035133 There was a slight typo in my query. Please have a look now.
Only 2 rows affected. I have 58045 rows need to be updated
It might be the condition WHERE ivr.ivno = 22664. But that is part of the original question, which is why I added it.
|

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.