October 26, 2012 at 7:57 am
Hi I am getting the following error message trying to pass a variable into an openquery, can someone point out how to correct the error: Incorrect syntax near '+'
Thank you very much...
declare @string varchar(max)
set @string = 'abcd'
select * from openquery
(TEST_Server, 'select * from Table1 where Field1 = ' + @string + '')
October 26, 2012 at 8:10 am
Try the following syntax
declare @string varchar(max)
set @string = 'abcd'
select * from openquery
(TEST_Server, 'select * from Table1 where Field1 = ' + @string + '')
October 26, 2012 at 8:14 am
Hi vyas, thank you for the reply. That's the same syntax that I originally had, or at least I can't see the difference in your query, am I missing something?
October 26, 2012 at 10:13 am
I think the problem is that you are declaring the variable outside the query. Try putting everything into the OpenQuery:
Select * from OpenQuery(TestServer,'declare @string varchar(max) Set @string=''abcd'' Select * From Table1 where Field1=@string')
HTH
Elliott
October 29, 2012 at 6:50 am
OPENQUERY does not accept variables for its arguments. If you need to build the query dynamically you can use dynamic SQL.
DECLARE @string VARCHAR(MAX),
@SQL NVARCHAR(MAX);
SET @string = 'abcd';
SET @SQL = 'SELECT * FROM OPENQUERY(TEST_Server, ''SELECT * FROM Table1 WHERE Field1 = ''''' + @string + ''''''')';
EXEC sp_executesql @SQL;
October 29, 2012 at 8:33 am
Re: "OpenQuery does not accept variables" --
This runs fine in my set-up:
Select * from OpenQuery(MyLinkedServer,'Declare @name varchar(50) Set @name=''RemoteDB'' Select * from sys.databases where name=@name')
Note the declaration of the variable within the query statement (and the assignment of a value with double quotes).
HTH
Elliott
October 29, 2012 at 8:39 am
Elliott Berkihiser (10/29/2012)
Re: "OpenQuery does not accept variables" --This runs fine in my set-up:
Select * from OpenQuery(MyLinkedServer,'Declare @name varchar(50) Set @name=''RemoteDB'' Select * from sys.databases where name=@name')
Note the declaration of the variable within the query statement (and the assignment of a value with double quotes).
HTH
Elliott
In your example, OpenQuery is not 'accepting' a variable. The OpenQuery argument is static, even though it contains a variable.
October 29, 2012 at 9:14 am
Yes, I agree.
August 30, 2019 at 7:48 am
how to pass the IN OPERATOR IN OPENQUERY, I AM NOT GETTING ON INTERNET. PLEASE HELP ABOUT THIS
Viewing 9 posts - 1 through 9 (of 9 total)
You must be logged in to reply to this topic. Login to reply
This website stores cookies on your computer.
These cookies are used to improve your website experience and provide more personalized services to you, both on this website and through other media.
To find out more about the cookies we use, see our Privacy Policy