Use Parameters with OPENQUERY in SQL

24. April 2008

Unfortunately, in the Microsoft SQL world, sometimes you have to deal with using OPENQUERY.  This is difficult to use sometimes because you don't have as much flexibility with variables and parameters as you would using normal T-SQL.  Below is an example of how you can use OPENQUERY and still utilize a variable or parameter.

DECLARE @variable VARCHAR(10)
DECLARE @sqlQuery VARCHAR(8000)
DECLARE @finalQuery VARCHAR(8000)

SET @variable = 'yourStringValue'

SET @sqlQuery = 'SELECT * FROM tableName WHERE strValue = ' + '''' + '''' + @variable + '''' + ''''

SET @finalQuery = 'SELECT * FROM OPENQUERY(LINKEDSERVER,' + '''' + @sqlQuery + '''' + ')'

--used for debugging
SELECT @finalQuery

EXEC(@finalQuery)

NOTE: It may be hard to see but the '''' is 4 single quotes

I recommend commenting out EXEC(@finalQuery) until you see @finalQuery correctly in the results.  Running SELECT @finalQuery is very helpful because you can see what single quotes are missing if need be. 

I also recommend getting your OPENQUERY statement to work correctly before trying to make it "dynamic" so to say using the above method.

Anyway, I found this very useful to use and hope that it can help some others out there.

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Microsoft SQL

Comments

4/24/2008 12:20:49 AM #
Trackback from DotNetKicks.com

Parameters in OPENQUERY
i was
4/25/2008 12:40:42 PM #
Thanks .you saved my lots of time.
Shanker
11/14/2008 5:21:25 PM #
Thank you so much!!!!!
John
12/9/2008 11:45:32 PM #
Thank you for your contribution.
Bhoju
12/31/2008 10:14:20 AM #
Thanks a lot, nice query
Carlos_V
3/31/2009 9:45:11 PM #
Excelente!!! pero le falta un apostrofe al final de la consulta, deberia ser asi:

SET @finalQuery = 'SELECT * FROM OPENQUERY(LINKEDSERVER,' + '''' + @sqlQuery + '''' + ''')'
Massimo
4/29/2009 5:59:58 PM #
Thank you so much!!!!!!!
Umer Tahir
6/10/2009 4:57:20 PM #
Thankyou mate, it works like a charm.
zaki
7/9/2009 11:19:47 AM #
Great, thank you!
James
9/8/2009 4:41:26 PM #
Thanks, John, for the tip.  How can I run a store procedure with parameter using your method?

Add comment




  Country flag

biuquote
  • Comment
  • Preview
Loading