If it is one and the same query that just needs to be executed in different contexts, you could try specifying the context by calling the corresponding instance of sp_executesql
to execute your dynamic query:
linkedserver.remotedatabase.sys.sp_executesql N'
SELECT
...
FROM dbo.Table1 AS a
INNER JOIN dbo.Table2 AS b ON ...
';
That way linkedserver.remotedatabase
would be the current database and indeed linkedserver
the current server of the specified query.
That method, however, might require an additional level of dynamicity since you are reading the names from a table. For the following illustration of how the query building part would look like in such a case, I am assuming that the names of the server and the database are stored in variables (as if, for instance, you have populated the vars in a cursor iteration):
DECLARE @sql nvarchar(max), @metasql nvarchar(max);
SET @sql = N'your dynamic query (without USE)';
SET @metasql = QUOTENAME(@servername) + N'.' + QUOTENAME(@databasename) + N'.sys.sp_execute @sql';
EXECUTE sp_execute @metasql, N'@sql nvarchar(max)', @sql;
This kind of double nesting may not be very good for the occasional debugging you are mentioning in one of your comments, though. But then you could go with incorporation of the @sql
's contents into @metasql
instead of parametrisation:
DECLARE @sql nvarchar(max), @metasql nvarchar(max);
SET @sql = N'your dynamic query (without USE)';
SET @metasql = QUOTENAME(@servername) + N'.' + QUOTENAME(@databasename) + N'.sys.sp_execute N' + QUOTENAME(@sql, '''');
EXECUTE sp_execute @metasql;