Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

EXEC sp_executesql: No cross server join

I’d like to execute following statement with a clause to prevent cross server joins:

SET @Sql = N'
    SELECT TOP(1) @CodeID = CodeType
    FROM ' + QUOTENAME(@Db) + '.bla.Field 
    WHERE Name = @SearchName'

EXEC sp_executesql @Sql,
    N'@SearchName NVARCHAR(256), @CodeID NVARCHAR(256) OUTPUT',
    @SearchName, @CodeID OUTPUT

For EXEC I use this statement:

  SET @Sql = 'EXEC (''' + REPLACE(@Sql, '''', '''''') + ''')' + CASE WHEN @ServerName = @ThisServer THEN '' ELSE ' AT ' + @ServerName END
    EXEC ( @Sql )

How do I adapt my statement to work with EXEC sp_executesql?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use the fact that the procedure name EXEC calls can be furnished via a variable. So that can be:

DECLARE @exec nvarchar(1000) = N'sys.sp_executesql';
EXEC @exec N'SELECT 1';

— or

DECLARE @exec nvarchar(1000) = QUOTENAME(@db) 
  + N'sys.sp_executesql';
EXEC @exec N'SELECT 1';

— or

DECLARE @exec nvarchar(1000) = QUOTENAME(@server)
  + QUOTENAME(@db) 
  + N'sys.sp_executesql';
EXEC @exec N'SELECT 1';

In your case:

DECLARE @Sql nvarchar(max) = N'
    SELECT TOP(1) @CodeID = CodeType
    FROM bla.Field 
    WHERE Name = @SearchName;';

DECLARE @exec nvarchar(1000) = CASE
  WHEN @ServerName = @ThisServer THEN N''
  ELSE QUOTENAME(@ServerName) + N'.' END
  + QUOTENAME(@db) + N'.sys.sp_executesql';

EXEC @exec @Sql,
    N'@SearchName NVARCHAR(256), @CodeID NVARCHAR(256) OUTPUT',
    @SearchName, @CodeID OUTPUT;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading