TSQL - how to execute a query as a variable?
t-sql, variables
Solution
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]
Problem
``` 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?