5

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

For example:

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

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

2 Answers 2

4

example

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

make sure to read The Curse and Blessings of Dynamic SQL to protect against SQL injection

Sign up to request clarification or add additional context in comments.

2 Comments

Isn't the closing bracket for openquery() missing?
12 years and 8 months later, I have a question. How do I create a view out of this query? I have a similar exec('select statement) at LinkedServer which works fine. Now I want to create a View which I will then use with Power BI. When I write the standard Create View Viewname AS exec('select statement) at LinkedServer.. I get an error because create view is expecting a select statement after AS... Kindly assist
2

see EXEC() at Linked Server section of The Curse and Blessings of Dynamic SQL by Erland Sommarskog

from that article:

A special feature added in SQL 2005 is that you can use EXEC() to run pass-through queries on a linked server. This could be another instance of SQL Server, but it could also be an Oracle server, an Access database, Active directory or whatever. The SQL could be a single query or a sequence of statements, and could it be composed dynamically or be entirely static. The syntax is simple, as seen by this example:

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

SQL2K is here a linked server that has been defined with sp_addlinkedserver.

2 Comments

doesn't work with a dynamically named linked server, this doesn't work...EXEC('SELECT COUNT(*) FROM dbo.sysobjects') AT @linkedServer
@SQLMenace, this will work EXEC ('EXEC(''SELECT COUNT(*) FROM ' + @db + '.dbo.sysobjects'') AT '+@linkedServer)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.