Make tables from different databases match each other
-
12-12-2019 - |
Domanda
I am trying to update a table so that all values become identical to another table on a different database. I can do it with an insert command but not an update command.
This works:
INSERT [test1].[dbo].[table1]
SELECT * FROM [source].[dbo].[table1]
This does not:
UPDATE [test2].[dbo].[table1]
SET [source].[dbo].[table1] = [test2].[dbo].[table1]
nor this:
UPDATE [test2].[dbo].[table1]
SET
[test2].[dbo].[table1].[PKcolumn] = [source].[dbo].[table1].[PKcolumn]
,[test2].[dbo].[table1].[column2] = [source].[dbo].[table1].[column2]
,[test2].[dbo].[table1].[column3] = [source].[dbo].[table1].[column3]
WHERE
[source].[dbo].[table1].[PKcolumn] = [test2].[dbo].[table1].[PKcolumn]
The result is always some variation of this error message despite checking for errors countless times:
Msg 4104, Level 16, State 1, Line 1
The multi-part identifier "source.dbo.table1.PKColumn" could not be bound.
Any Suggestions?
Soluzione
Since update
can only affect one table, you don't have to specify it:
UPDATE dest
SET column2 = src.column2
FROM source.dbo.table1 as src
JOIN test2.dbo.table1 as dest
on dest.PKcolumn = src.PKcolumn
P.S. Depending on which database you're using, you might want to check out the MERGE
statement.
Altri suggerimenti
You are missing the FROM clause (since you are using a multiple tables in an update clause) Check this: http://scottonwriting.net/sowblog/archive/2010/07/13/howto-update-records-in-a-database-table-with-data-from-another-table-ms-sql-server.aspx
Try this:
UPDATE [test2].[dbo].[table1]
SET
[test2].[dbo].[table1].[PKcolumn] = [source].[dbo].[table1].[PKcolumn]
,[test2].[dbo].[table1].[column2] = [source].[dbo].[table1].[column2]
,[test2].[dbo].[table1].[column3] = [source].[dbo].[table1].[column3]
FROM [source].[dbo].[table1] JOIN [test2].[dbo].[table1]
ON
[source].[dbo].[table1].[PKcolumn] = [test2].[dbo].[table1].[PKcolumn]