0

I have two tables which looks like this:

Table1(ID, name, street, houseNo, DeliveryID) and Table2(ID, name street houseNo, DeliveryID)

I want to create a procedure that checks the contents of Table1(name, street, houseNo) and Table2(name, street houseNo). And if the content is equal to each other it should insert Table1.DeliveryID into Table2.DelvieryID.

how would i do that ?

2
  • are the two tables related with each other? Commented Apr 24, 2013 at 6:01
  • @JW웃 nope they are not Commented Apr 24, 2013 at 6:04

3 Answers 3

3

Please try using inner join update (SQL Server Update with Inner Join):

UPDATE Table2
SET Table2.DelvieryID = Table1.DelvieryID
FROM Table2, Table1
WHERE 
    Table2.name = Table1.name AND
    Table2.street = Table1.street AND
    Table2.houseNo = Table1.houseNo 

For considering NULL values, try

UPDATE Table2
SET Table2.DelvieryID = Table1.DelvieryID
FROM Table2, Table1
WHERE 
    ISNULL(Table2.name, '') = ISNULL(Table1.name, '') AND
    ISNULL(Table2.street, '') = ISNULL(Table1.street, '') AND
    ISNULL(Table2.houseNo, '') = ISNULL(Table1.houseNo, '') 
Sign up to request clarification or add additional context in comments.

8 Comments

Some of them are nulls and i can see that i cant compare nulls. How can i get around that issue ?
You asked for an INSERT - this is an UPDATE
Means you don't need to update DeliveryID if both table columns are NULL?
@techdo no i mean that houseNO in both tables can be NULL. And if that is the case then i wouldnt be able to find the right row. Can i convert the rows with NULLs to something else that can be compared ?
@ElectricLlama you UPDATE the row by inserting Table1.DeliveryID into Table2.DeliveryID
|
3
UPDATE Table2
SET Table2.DelvieryID = Table1.DelvieryID
FROM Table1 t1, Table2 t2
WHERE CHECKSUM(t1.name,t1.street,t1.houseNo)=CHECKSUM(t2.name,t2.street,t2.houseNo)

Comments

2

Simple joins will work ..

UPDATE tab2
SET tab2.DelvieryID = tab1.DelvieryID
FROM Table2 tab2, Table1 tab1
WHERE 
tab2.name = tab1.name AND
tab2.street = tab1.street AND
tab2.houseNo = tab1.houseNo

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.