views:

81

answers:

2

I'm trying to run the following TSQL statement on Microsoft SQL 2008

DECLARE @tmpMessage nvarchar(max)

SET @tmpMessage = 'select * from openquery(GLive,''select ID from Links WHERE [HREF] LIKE ''test'''')';

exec sp_executesql @tmpMessage

the above code doesnt work because the single quotes before test closes the main quotes around the second select statement select ID from Links ....

and yes i have to put my statement in a string first before executes it because openquery function wont allow me to do somethin like

select * from openquery(GLive,'select ID from Links WHERE [Href] LIKE ''' + @Var + ''''')

any suggesstions would be appreciated.

thanks in advance.

A: 

You might also try out the QUOTENAME command.

Brad
Only works for strings <= 128 characters AFAIK.
Martin Smith
it kinda worked for me after removing the '[' and ']' the quotename function added, thanks
Ahmed Galal
A: 

Here is a template that I use whenever I'm dealing with variables in an openquery statement to a linked server:

DECLARE @UniqueId int
, @sql varchar(500)
, @linkedserver varchar(30)
, @statement varchar(600)

SET @UniqueId = 2

SET @linkedserver = 'LINKSERV'
SET @sql = 'SELECT DummyFunction(''''' + CAST(@UniqueId AS VARCHAR(10))+ ''''') FROM DUAL'
SET @statement = 'SELECT * FROM OPENQUERY(' + @linkedserver + ', ' 
SET @Statement = @Statement + '''' +  @SQL + ''')'
EXEC(@Statement)
CletusLoomis
yes nice idea to split it into 2 strings, thanks it works
Ahmed Galal