1

I need to reach a return value from Dynamic SQL. I execute select query as string with sp_executesql. I have to reach results. Here is sql query:

DECLARE @dynsql nvarchar(max)  
SET @dynsql = 'select @InvoiceNo=InvoiceNo from '+ QUOTENAME(@DynDB) +'.[dbo].[TableName] where UserID = '+ 
        cast(@UserID as nvarchar) 
EXEC sp_executesql @dynsql

Problem: This @dynsql is string value and I have to reach a value in this sql query.

1 Answer 1

1

The best solution is:

We can add our output parameter to query then we should add it to execute line like this:

DECLARE @dynsql nvarchar(max)  
SET @dynsql = 'select @InvoiceNo=InvoiceNo from '+ QUOTENAME(@DynDB) +'.[dbo].[TableName] where UserID = '+ 
        cast(@UserID as nvarchar) 
EXEC sp_executesql @dynsql, N'@InvoiceNo int OUTPUT',@InvoiceNo = @InvoiceNo OUTPUT
select @InvoiceNo as InvoiceNo

And the result is: InvoiceNo = 11111 (int value)

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

1 Comment

This is awesome.

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.