Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set EXECUTE sp_executesql result into a variable in sql

I have to set a dynamic sql query result to a variable. My sql query is :

DECLARE @ResultString NVARCHAR(MAX)
DECLARE @Qry NVARCHAR(MAX)  

SET @Qry='SELECT Test FROM MTest22Dec WHERE ID = 1'      
EXECUTE sp_executesql @Qry, N'@Result NVARCHAR(MAX) OUTPUT', @Result=@ResultString OUTPUT
PRINT @ResultString

But @ResultString is printing empty string although there is record in database table.

What is wrong in this query?

thanks

like image 867
Kartikeya Khosla Avatar asked Jan 02 '15 06:01

Kartikeya Khosla


People also ask

How do you store a result of query in a variable in SQL Server?

This provides a way to save a result returned from one query, then refer to it later in other queries. The syntax for assigning a value to a SQL variable within a SELECT query is @ var_name := value , where var_name is the variable name and value is a value that you're retrieving.

What is EXEC sp_executesql in SQL?

What is the sp_executesql stored procedure? A SQL Server built-in stored procedures used to run one or multiple SQL statements stored within a string. This stored procedure allows executing static or strings built dynamically.


1 Answers

You need to assign the result of select to variable inside Dynamic statement.

Change you query like this.

DECLARE @Result NVARCHAR(MAX)
DECLARE @Qry NVARCHAR(MAX)

SET @Qry='SELECT @Result = Test FROM MTest22Dec WHERE ID = 1'

EXECUTE Sp_executesql @Qry, N'@Result NVARCHAR(MAX) OUTPUT', @Result OUTPUT

PRINT @Result 
like image 124
Pரதீப் Avatar answered Oct 12 '22 14:10

Pரதீப்