Dynamic Link Server Request

Is it possible to build a dynamic query for a linked server (and if so, how)?

For instance:

@linkedServer varchar(50)
@var1 varchar(10)
@var2 varchar(10)

select * 
  from openquery(@linkedServer, 
                 'select c1,c2 
                    from t1 
                   where p1 = @var1 
                     and p2= @var2')
+5
source share
2 answers

Example

exec ('select * from openquery(' + @linkedServer + 
', ''select c1,c2 from t1 where p1 = '' + @var1 + ''and p2= '' + @var2 + ''')

be sure to read the Curse and blessings of dynamic SQL to protect against SQL injection

+4
source

see EXEC () in the Linked Server section of The Curse and Blessings of Dynamic SQL by Erland Sommargog

from this article:

SQL 2005 ​​ EXEC() . SQL Server, Oracle, Access, - . SQL , . , :

EXEC ('SELECT COUNT (*) FROM' + @db + '.dbo.sysobjects') AT SQL2K

SQL2K - , sp_addlinkedserver.

+2

All Articles