DECLARE @query as varchar(200);
SET @query = 'SELECT COUNT(*) FROM table';
How can I execute @query
, and additionally, is there way to store the query result directly when assigning the variable?
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. The variable may be used in subsequent queries wherever an expression is allowed, such as in a WHERE clause or in an INSERT statement.
To run a dynamic SQL statement, run the stored procedure sp_executesql as shown below : EXEC sp_executesql N'SELECT statement'; Use prefix N with the sp_executesql to use dynamic SQL as a Unicode string.
Variables in SQL procedures are defined by using the DECLARE statement. Values can be assigned to variables using the SET statement or the SELECT INTO statement or as a default value when the variable is declared. Literals, expressions, the result of a query, and special register values can be assigned to variables.
You can use sp_executesql
with an output
parameter to retrieve the scalar result.
DECLARE @query as nvarchar(200), @count int;
SET @query = N'SELECT @count = COUNT(*) FROM table';
EXEC sp_executesql @query,
N'@count int OUTPUT',
@count = @count OUTPUT
SELECT @count AS [@count]
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