3

I wanted to assign value to out variable inside a dynamic query.

SET @query = 'IF EXISTS(Condition)
BEGIN
  --Some action goes here
  SET @result= 1
END
ELSE
BEGIN
  SET @result= 2
END'
EXEC(@query)

When am trying to execute this query, I am getting an error:

Must declare the scalar variable "@result".

How can I set value to variable inside dynamic query?

Thanks in advance.

0

2 Answers 2

4

Just try this:

DECLARE @result INT
       ,@query NVARCHAR(MAX);

SET @query = 'IF (1 = 0)
BEGIN
  --Some action goes here
  SET @result= 1
END
ELSE
BEGIN
  SET @result= 2
END';

EXEC sp_executesql @query, N'@result INT OUTPUT',@result =  @result OUTPUT

SELECT @result;

You can use sp_executesql in order to execute dynamic T-SQL statement and initialize SQL variables. In the sp_executesql you need to pass the parameter definition and then parameter mappings.

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

1 Comment

@RaJeshRiJo You need to insure that the @query parameter and the parameters definitions are in type nvarchar
1

When you Execute a Query String, It is Considered as a separate session, so The variables that you have declared in the current windows won't be accessible whereas you can access the Temporary tables.

So you have to declare the variable inside the string. Your Query can be re-written as below

SET @query = '
DECLARE @result INT
IF EXISTS(Condition)
BEGIN
  --Some action goes here
  SET @result= 1
END
ELSE
BEGIN
  SET @result= 2
END'
EXEC(@query)

Or Store the result in a table variable and access it from there

DECLARE @Tablevar TABLE
(
 Result INT
)

SET @query = '
    IF EXISTS(Condition)
    BEGIN
      --Some action goes here
      select 1
    END
    ELSE
    BEGIN
      SELECT 2
    END'

INSERT INTO @Tablevar 
    EXEC(@query)

select @Result = Result FROM @Tablevar 

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.