这是我到目前为止所拥有的。我想将查询结果存储到int变量中,但到目前为止我得到null。执行后,@ query和@countrow都为null。任何建议都会很棒。
SET @query = N'select @countrow=count(*) from ' + @tablename
EXECUTE sp_executesql @query
答案 0 :(得分:3)
DECLARE @i INT, @sql NVARCHAR(512), @tablename varchar(200) = 'tbl'
SET @sql = N'SELECT @i = COUNT(*) FROM ' + @tablename
EXEC sp_executesql
@query = @sql,
@params = N'@i INT OUTPUT',
@i = @i OUTPUT
PRINT @i
答案 1 :(得分:2)
您需要使用OUTPUT
关键字,类似于:
declare @query nvarchar(max)
declare @countrow int
declare @tablename varchar(50)
SET @query = N'select @cnt=count(*) from ' + @tablename
EXECUTE sp_executesql @query, N'@cnt int OUTPUT', @cnt=@countrow OUTPUT
select @countrow as countrow -- to get the result