Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TSQL - how to execute a query as a variable?

Tags:

variables

tsql

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?

like image 404
Malyo Avatar asked May 28 '12 08:05

Malyo


People also ask

How do I run a SQL query in a 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.

How do I run a dynamic SQL query?

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.

How do you DECLARE a variable in SQL and use it in query?

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.


1 Answers

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]
like image 168
Martin Smith Avatar answered Sep 29 '22 11:09

Martin Smith