0

I am getting an error running the code below. I believe it as to do with the number of single quotes used. How can I set a variable inside OPENQUERY command?

@declare @myStr varchar(6)
set @myStr = 'Test1'

SELECT *    
FROM OPENQUERY("192.168.1.1",'SET FMTONLY OFF; EXEC spNewTest @Param1 = ''+ @myStr +''')

Click to see the error message

Regards, Elio Fernandes

Elio Fernandes
  • 1,335
  • 2
  • 14
  • 29

2 Answers2

1

If you want to create a single quote within a string you have to put in two single quotes. For example: '''this is a string''' would be a string containing the following: 'this is a string'

So for your problem, you have to change your code to this:

@declare @myStr varchar(6)
set @myStr = 'Test1'

SELECT *    
FROM OPENQUERY("192.168.1.1",'SET FMTONLY OFF; EXEC spNewTest @Param1 = '''+ @myStr +'''')
Markai
  • 2,098
  • 1
  • 10
  • 15
1

I just found the answer for my question, so I thought sharing it with you.

DECLARE @QUERY VARCHAR(MAX)
DECLARE @TSQL VARCHAR(100)
DECLARE @SP VARCHAR(50)

DECLARE @PARAMETERS VARCHAR(MAX)
DECLARE @PARAM1 VARCHAR(50)
DECLARE @PARAM2 VARCHAR(50)

SET @TSQL = N'SELECT * FROM OPENQUERY([192.168.1.1], ''SET FMTONLY OFF; '
SET @SP   = 'EXEC spNewTest '

SET @PARAM1 = '@Type='''+ QUOTENAME('Test','''') + ''''
SET @PARAM2 = '@Year='''+ QUOTENAME('2016','''') + ''''
SET @PARAMETERS = @PARAM1 + ', ' + @PARAM2

SET @QUERY = @TSQL + @SP + @PARAMETERS + ''')'

EXECUTE (@QUERY)

Thanks

Elio Fernandes
  • 1,335
  • 2
  • 14
  • 29