4

How do I use output parameters with Character String Exec? Consider following query with "standard" syntax:

DECLARE @testString nvarchar(50);
EXEC testProcedure  @param1 = @testString OUTPUT
SELECT 'result ' = @testString
go

How to re-create exactly same result with character string exec, neither

EXEC ( 'testProcedure @param1 = @testString OUTPUT' )

nor

EXEC ( 'testProcedure @param1 = ' + @testString + ' OUTPUT' )

seems to work: the result is either NULL or Must declare the scalar variable "@testString" error.

1 Answer 1

6

You need to pass the value as a parameter. Dynamic SQL is executed in new context that is why variable is not visible there.

You should use sp_executesql:

DECLARE @testString nvarchar(50);

EXEC dbo.sp_executesql N'EXEC testProcedure @testString OUTPUT',
                       N'@testString nvarchar(50) OUTPUT',
                       @testString OUTPUT;

SELECT 'result ' = @testString;

LiveDemo

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

1 Comment

Is it possible to return in dynamic SQL something like @a = exec (@sql). @a is coming from return value of proc not output param.

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.