Linked Servers: Performing Select, Insert, Update and Delete (CRUD) actions
You could literally spend hours combing the internet trying to figure out how to do something.
In my last post, I spend 4 hours trying to figure out exactly how to get a linked server working with SQL Server. After I finally getting the server linked so I could perform simple queries against it, I needed to now figure out how I could perform inserts, updates and deletes to it.
Scouring the internet again proved totally a waste of time and I decide to just try to figure it out on my own. Well after another 2 hours, I have figured it out. Here is the syntax to do select, insert, update, and delete (CRUD) actions against a linked server. Remember that your syntax might vary slightly. All queries use the OPENQUERY command.
SELECT:
select * from openquery(‘my_linked_server’, ‘select * from table_schema.table_name’)
INSERT:
insert openquery(‘my_linked_server, ‘select column_1, column2 from table_schema.table_name’)
values (‘my_value1′, ‘my_value2′)
UPDATE:
update openquery(‘my_linked_server, ‘select column_1, column_2 from table_schema.table_name where pk = pk_value’)
set column_1 = ‘my_value1′, column_2 = ‘my_value2′
DELETE:
delete from openqueryopenquery(‘my_linked_server, ‘select * from table_schema.table_name where pk = pk_value’)
There you have it, I just saved you 2 hours (can I get mine back).
Nice job – books online was startlingly unhelpful, as usual.
You have indeed saved me at least two hours.
Keep up the good work.
It’s what I’m here for
Well, why not use LinkedServerName.Database.dbo.TableName. There is however some interesting performance issues to take into consideration when inserting into a linked server. It seems as if SQL does the inserts post by post.
Thank you. You saved my time.
Thanks, saved me a bunch of time.
Just learning SQL and setting up Linked Servers.
Mike
Regarding what Magnus said above:
“Well, why not use LinkedServerName.Database.dbo.TableName. ”
Well, because it does not work.
Note that this facility would depend upon what capabilities the driver provides for a given linked server. So if you are just linking two SQL Server dbs together, yeah, maybe that would work. But if you are linking to MySQL, guess what happens when you try that:
—————————–
Invalid use of schema or catalog for OLE DB provider “MSDASQL” for linked server “wqx”. A four-part name was supplied, but the provider does not expose the necessary interfaces to use a catalog or schema.
—————————–
So this error tells us the ‘provider’ (i.e., data source driver) does not give us this interface for this database.
Thanks to the person who left this information. You have helped a lot of people with your efforts.
Magnus said, on April 8, 2008 at 2:07 am
Well, why not use LinkedServerName.Database.dbo.TableName.
——————————————————————————-
Because that does not work with many types of database drivers. It will produce an error with drivers that do not support that syntax, such as mysql.