I have a database with account numbers
and card numbers
. I match these to a file to update
any card numbers to the account number, so that I am only working with account numbers.
I created a view linking the table to the account/card database to return the Table ID
and the related account number, and now I need to update those records where the ID matches with the Account Number.
This is the Sales_Import
table, where the account number
field needs to be updated:
LeadID AccountNumber
147 5807811235
150 5807811326
185 7006100100007267039
And this is the RetrieveAccountNumber
table, where I need to update from:
LeadID AccountNumber
147 7006100100007266957
150 7006100100007267039
I tried the below, but no luck so far:
UPDATE [Sales_Lead].[dbo].[Sales_Import]
SET [AccountNumber] = (SELECT RetrieveAccountNumber.AccountNumber
FROM RetrieveAccountNumber
WHERE [Sales_Lead].[dbo].[Sales_Import]. LeadID =
RetrieveAccountNumber.LeadID)
It updates the card numbers to account numbers, but the account numbers gets replaced by NULL
Here's what worked for me in SQL Server:
it works with postgresql
For SQL Server 2008 + Using
MERGE
rather than the proprietaryUPDATE ... FROM
syntax has some appeal.As well as being standard SQL and thus more portable it also will raise an error in the event of there being multiple joined rows on the source side (and thus multiple possible different values to use in the update) rather than having the final result be undeterministic.
Unfortunately the choice of which to use may not come down purely to preferred style however. The implementation of
MERGE
in SQL Server has been afflicted with various bugs. Aaron Bertrand has compiled a list of the reported ones here.Seems you are using MSSQL, then, if I remember correctly, it is done like this:
The below SQL someone suggested, does NOT work in SQL Server. This syntax reminds me of my old school class:
All other queries using
NOT IN
orNOT EXISTS
are not recommended. NULLs show up because OP compares entire dataset with smaller subset, then of course there will be matching problem. This must be fixed by writing proper SQL with correctJOIN
instead of dodging problem by usingNOT IN
. You might run into other problems by usingNOT IN
orNOT EXISTS
in this case.My vote for the top one, which is conventional way of updating a table based on another table by joining in SQL Server. Like I said, you cannot use two tables in same
UPDATE
statement in SQL Server unless you join them first.If above answers not working for you try this