简体   繁体   中英

Passthrough Query from one SQL Server to another that drops a table on the source

I have a SQL Server in Spain and one in the US and there is a domain trust between the two with linked servers on each for access to the other.

I would like to be able to run the below query on the US SQL Server without having to maintain a stored proc on the US Server in order to run it. Is there a way to create a passthrough query from the SQL Server in Spain? I've already tried using OPENQUERY and OPENROWSET and it's just not working as they only seem to work with select statements that return results:

DROP TABLE IF EXISTS [Global].[dbo].[WW_Customer_Receivables]

SELECT * 

INTO [global].[dbo].[ww_customer_receivables]

FROM 
    [LinkedServerObject-Spain].[global].dbo.ww_customer_receivables

If you want to execute DDL statement on your linked server with openquery you can with the following trick:

SELECT *
FROM OPENQUERY(linkedserver, '
DROP TABLE IF EXISTS [Global].[dbo].[WW_Customer_Receivables]
SELECT @@RowCount')

The SELECT @@RowCount returns a result set. So OPENQUERY works. This trick works for all DDL operations like create, alter, drop. Or if you want to perform inserts/updates/deletes that don't return a result set.

Same trick is applied here Where they have a dummy select foobar.

If you want to execute the into statement from the openquery you can do it like this:

DROP TABLE IF EXISTS [Global].[dbo].[WW_Customer_Receivables]

SELECT *
INTO [global].[dbo].[ww_customer_receivables]
FROM OPENQUERY([LinkerServerObject-US], '
    SELECT *
    FROM [global].dbo.ww_customer_receivables')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM