0

I have an id and abbreviation column in a table. I would like to update the abbreviation column in another database on another server.. I know how to get a SQL select statement, but how would I get an UPDATE statement from this that to run on the other database?

Basically I want to get something like:

UPDATE table SET abbrv=x WHERE id=1;
UPDATE table SET abbrv=y WHERE id=2;

...

How would I do this?

David542
  • 104,438
  • 178
  • 489
  • 842

2 Answers2

0

An easy way to do this is create a SELECT statement to generate the UPDATE statements:

SELECT 
    CONCAT('UPDATE home_provider SET abbrv="', abbrv, '" WHERE id=', id, ';')
FROM home_provider

This will then give you:

UPDATE home_provider SET abrv="ACA" WHERE id=1;
UPDATE home_provider SET abrv="ALL" WHERE id=2;
UPDATE home_provider SET abrv="ARK" WHERE id=3;
UPDATE home_provider SET abrv="ART" WHERE id=4;
...
Barmar
  • 741,623
  • 53
  • 500
  • 612
David542
  • 104,438
  • 178
  • 489
  • 842
0

assuming that there is a trust relationship between the two databases you can do an update with a join:

UPDATE target
SET target.abbrv = source.abbrv
FROM db1.dbo.table1 target
INNER JOIN db2.dbo.table1 source ON target.id = source.id

In the example above db1 would be the target database (where the information is updated) and db2 is the source database (where the data is copied from) and of course table1 would need to be changed to reflect the actual name of the table.

You can also include a where clause if you needed.

UPDATE target
SET target.abbrv = source.abbrv
FROM db1.dbo.table1 target
INNER JOIN db2.dbo.table1 source ON target.id = source.id
WHERE target.id in (1,2,3,5)

If the databases are on separate servers:

UPDATE target
SET target.abbrv = source.abbrv
FROM servara.db1.dbo.table1 target
INNER JOIN serverb.db2.dbo.table1 source ON target.id = source.id
Austin
  • 754
  • 8
  • 12
  • Can swear you can just do: UPDATE target SET abbrv = abbreviation FROM servera.dbo.table tbs WHERE target.ID = tbs.ID – Dylan Brams Dec 31 '13 at 01:04
  • @Dylan Yes, however you need the inner join. The where clause is only if you want to limit the update to a specific subset of records, otherwise, for every matching table between source and target it will be updated. – Austin Dec 31 '13 at 01:53
  • here is a sqlfiddle to demonstrate the concept: http://sqlfiddle.com/#!6/d451c/1 not sure if I am sharing the fiddle correctly (I just found this site two days ago) – Austin Dec 31 '13 at 02:07