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
For MySql that works fine:
UPDATE
Sales_Import SI,RetrieveAccountNumber RAN
SET
SI.AccountNumber = RAN.AccountNumber
WHERE
SI.LeadID = RAN.LeadID
Use the following block of query to update Table1 with Table2 based on ID:
UPDATE Sales_Import, RetrieveAccountNumber
SET Sales_Import.AccountNumber = RetrieveAccountNumber.AccountNumber
where Sales_Import.LeadID = RetrieveAccountNumber.LeadID;
This is the easiest way to tackle this problem.
I thought this is a simple example might someone get it easier,
DECLARE @TB1 TABLE
(
No Int
,Name NVarchar(50)
)
DECLARE @TB2 TABLE
(
No Int
,Name NVarchar(50)
)
INSERT INTO @TB1 VALUES(1,'asdf');
INSERT INTO @TB1 VALUES(2,'awerq');
INSERT INTO @TB2 VALUES(1,';oiup');
INSERT INTO @TB2 VALUES(2,'lkjhj');
SELECT * FROM @TB1
UPDATE @TB1 SET Name =S.Name
FROM @TB1 T
INNER JOIN @TB2 S
ON S.No = T.No
SELECT * FROM @TB1
For SQL Server 2008 + Using MERGE
rather than the proprietary UPDATE ... 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.
MERGE INTO Sales_Import
USING RetrieveAccountNumber
ON Sales_Import.LeadID = RetrieveAccountNumber.LeadID
WHEN MATCHED THEN
UPDATE
SET AccountNumber = RetrieveAccountNumber.AccountNumber;
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.
I had the same problem with foo.new
being set to null
for rows of foo
that had no matching key in bar
. I did something like this in Oracle:
update foo set foo.new = (select bar.new from bar where foo.key = bar.key) where exists (select 1 from bar where foo.key = bar.key)
This will allow you to update a table based on the column value not being found in another table.
UPDATE table1 SET table1.column = 'some_new_val' WHERE table1.id IN (
SELECT *
FROM (
SELECT table1.id
FROM table1
LEFT JOIN table2 ON ( table2.column = table1.column )
WHERE table1.column = 'some_expected_val'
AND table12.column IS NULL
) AS Xalias
)
This will update a table based on the column value being found in both tables.
UPDATE table1 SET table1.column = 'some_new_val' WHERE table1.id IN (
SELECT *
FROM (
SELECT table1.id
FROM table1
JOIN table2 ON ( table2.column = table1.column )
WHERE table1.column = 'some_expected_val'
) AS Xalias
)