Update database table from one SQL Server database table to another?

Viewed 77818

I am trying to update database fields from one SQL Server table to another.

Our production SQL Server is [spdbprod.test.com\spprod], our QA server is [spdbQA.test.com\spQA].

I need to update table in production from QA table. I using this SQL statement but, it is giving an error.

UPDATE 
    [spdbprod.test.com\spprod].[aspnetdb].[dbo].[Communities_Groups] as t1
SET 
    t1.Show = (Select t2.show from [spdbQA.test.com\spQA].[aspnetdb].[dbo].
[Communities_Groups] as t2 where t1.GroupID = t2.GroupdID)

What I am missing here? Error: UPDATE. ("Incorrect syntax near the keyword 'as'.")

4 Answers

I know this has been answered already but this worked for me.

  • Add a Linked Server under Server Objects | Linked Servers: Microsoft documentation.
  • Name the Linked Server [SERVER-NAME or <some ipaddress>, <some-port>]

    e.g. [10.0.0.200,2345] - I am using port 2345 but the standard MS SQL port is 1433.

Example:

  • We have a [Customers] table
  • We want to update [CustomerAddress]-field for CustomerId = 123
  • We want to use backup data from a server called [backupServer]
  • The [backupServer] is the machine where we execute the SQL

This is the SQL-code:

UPDATE production
SET
    CustomerAddress = backupServer.CustomerAddress
FROM 
    [10.0.0.200,2345].[ProductionDatabase].[dbo].[Customers] production
INNER JOIN 
    [BackupDatabase].[dbo].[Customers] backupServer
        ON 
            production.CustomerId = backupServer.CustomerId
WHERE 
    backupServer.CustomerId = 123

Generalized format:

UPDATE production
SET
    columnName = backupServer.columnName
FROM 
    [SERVER-NAME or IP,PORT].[ProductionDatabase].[dbo].[tableName] production
INNER JOIN 
    [BackupDatabase].[dbo].[tableName] backupServer
        ON 
            production.SomeId = backupServer.SomeId
WHERE 
    backupServer.SomeId = <id>
  1. You need to add a Linked Server under Server Objects
  2. You can name that Linked Server either with "CHOOSEN-NAME" or [ipaddress , port number]

how to add a linked server using tsql , please check this link : how to find linked server

for an example purpose suppose i have named the linked server "DESTINATION_SERVER" , database name is "DESTINATION_DB" and table name is "DESTINATION_TBL". then from your source server your query could be like this below:

UPDATE t1  
SET t1.updatecolumn = t2.updatecolumn
FROM [DESTINATION_SERVER].[DESTINATION_DB].[dbo].[DESTINATION_TBL] t1
INNER JOIN [SOURCE-SERVER].[SOURCE_DB].[dbo].
[SOURCE_TBL] t2 ON (t1.matcingcolumn = t2.matchingcolumn)
Related