Below is the query to get count in a variable whether the count statement is in a dynamic query.
USE Northwind
DECLARE @tablevariable varchar(100)
SET @tablevariable = 'Categories'
DECLARE @sql nvarchar(4000), @params nvarchar(4000), @count int
SELECT @sql = N' SELECT @cnt = COUNT(*) FROM ' + quotename(@tablevariable)
SELECT @params = N'@cnt int OUTPUT'
EXEC sp_executesql @sql, @params, @cnt=@count OUTPUT
SELECT @count
Note: sp_executesql is a system defined store procedure
No comments:
Post a Comment