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
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 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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With