1

I need to select value from SQL Linked Server & get it to loacal variable

This is what I've written so far:

DECLARE @SQLQUERY AS VARCHAR(1000)
DECLARE @FINALQUERY AS VARCHAR(1000)
DECLARE @OutVal AS VARCHAR(10)

SET @SQLQUERY = 'SELECT Field1 FROM Table1 WHERE Field2=' + CAST(@var1 AS VARCHAR) 
SET @FINALQUERY = 'SELECT @OutVal=Field1 FROM OPENQUERY(LINKEDSERVER,' + '''' + @SQLQUERY + '''' + ')'
EXEC(@finalQuery)

but this is wrong as it does not set the local variable(@OutVal).

2 Answers 2

2

Instead of exec, use sp_execute_sql with an output parameter:

exec sp_executesql @FinalQuery, N'@OutVal output', @OutVal = @OutVal out

Since sp_executesql expects nvarchar parameters, be sure to change the definition of @FinalQuery to nvarchar(max).

Sign up to request clarification or add additional context in comments.

Comments

1

@OutVal in query string does not recognized as a variable. use a function or return table statement.

Comments

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.