0

I have a stored procedure that I need to convert so that it reads a linked server variable from a table. From what I know, the only way to do so is to use dynamic SQL. The problem is that I'm failing to convert my query.

Original query:

SET @var1 = ''
SELECT  @var1 = RECEIVER        
FROM    databse1.dbo.table1 
WHERE   SAPNUMBER = @var2

Converted query:

SET @srv = (SELECT server_name
            FROM Configuration.dbo.Server_Switch)

SET @var1 = ''
exec (  
'SELECT ' + @var1 + '= RECEIVER
FROM ' + @srv + '.databse1.dbo.table1 
WHERE SAPNUMBER =' + @var2
)

The error that I'm getting is:

Incorrect syntax near '='

@var1 and @var2 are variables declared beforehand. I'm pretty sure there's a problem in assigning values to these variables in dynamic SQL, hence the '=' error. Can I get some help in converting this query?

1
  • Why do you think that dynamic sql would solve any problem at all? The only thing it would do was increase the possibility of problems. Imagine if someone stored a Bobby Tables in that Server_Switch table .... Commented Jan 19, 2017 at 13:35

2 Answers 2

4

One way to solve it is to use sp_executeSql with an output parameter:

SET @srv = (SELECT server_name
            FROM Configuration.dbo.Server_Switch)

DECLARE @sql nvarchar(500),
        @ParmDefinition nvarchar(500);

SET @sql = 
'SELECT @output = RECEIVER
FROM ' + @srv + '.databse1.dbo.table1 
WHERE SAPNUMBER =' + @var2

SET @ParmDefinition = N'@var1 varchar(100) OUTPUT';

EXEC sp_executesql @Sql, @ParmDefinition, @var1=@output OUTPUT;
Sign up to request clarification or add additional context in comments.

Comments

0

Please provide more info. We need variables @var2, @var1 declaration, types of variables. If @var2 is varchar, then please update your query in followoing way:

declare @sql nvarchar(4000) = 
'SELECT ' + @var1 + '= RECEIVER
FROM ' + @srv + '.databse1.dbo.table1 
WHERE SAPNUMBER =' + char(39) + @var2 + char(39);

exec(@sql); 

P.S. if @var2 numeric:

declare @sql nvarchar(4000) = 
'SELECT ' + @var1 + '= RECEIVER
FROM ' + @srv + '.databse1.dbo.table1 
WHERE SAPNUMBER =' + @var2;
exec(@sql); 

1 Comment

And finally I understood, that your target was to get value in @var1, not get the recordset. At this case you need to use sp_executesql with output, as said Zohar Peled

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.