Pass text to OpenQuery function

Trying to query a linked server using a parameter. Can't seem to pass a string to the OpenQuery function
For example:

Select @TSQL = 'select product_id_i, prod_stl_days_i from product where product_id_i=259287'

Select * From OpenQuery([MUNIPRIME],  'select product_id_i, prod_stl_days_i from product where product_id_i=259287' ) A
Select * From OpenQuery([MUNIPRIME], @TSQL ) A

The first select will work. The second select using the same string will give the error
Msg 170, Level 15, State 1, Line 10
Line 10: Incorrect syntax near '@TSQL'.

Can someone tell me what's going on?
LVL 2
stopher2475Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Reza RadConsultant, TrainerCommented:
try this:

SET @sql_str = N'select * from OPENQUERY([MUNIPRIME], ''' + REPLACE(@TSQL, '''', '''''') + ''')'

PRINT @sql_str

EXEC (@sql_str)
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
QlemoBatchelor, Developer and EE Topic AdvisorCommented:
The Book Onlines states clearly that you cannot use any variables for OpenQuery arguments. You need to use dynamic SQL, as shown above.
0
stopher2475Author Commented:
Thanks for the help. Found some other people with the same issue. They were pointed to here:
http://www.sommarskog.se/dynamic_sql.html#OPENQUERY
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.