我有一个要求,我必须找出已在主表中列出的每个表名的记录数。
主表看起来像: RecordId,TableName,RowCount 最初RowCOunt的所有行都设置为0。
我做的是,创建了一个光标
declare @tName nvarchar(max)
declare @query nvarchar(max)
declare @count int = 0
declare curCount cursor for select TableName from MasterTable
open curCount
fetch next from curCount into @tName
while @@fetch_status=0
begin
set @tName = @tName
set @query = N'select count(ID) from ['+@tName+']';
set @count = execute @query
update @tempTbl set RecordCount = @count where TableName = @tName
print @query
fetch next from curCount into @tName
end
close curCount
deallocate curCount
在这一点上每次都给我错误 设置@count = execute @query,错误是:关键字'exec'附近的语法不正确。
我也尝试了sp_executesql @query ...它也给了我错误,错误是'@query'附近的语法不正确。
请帮我解决这个问题。
答案 0 :(得分:0)
您可以将sp_executesql与输出参数一起使用来获取值。 请试试这个:
declare @tName nvarchar(max)
declare @query nvarchar(max)
declare @count int = 0
declare curCount cursor for select TableName from MasterTable
open curCount
fetch next from curCount into @tName
while @@fetch_status=0
begin
set @tName = @tName
set @query = N'select count(ID) from ['+@tName+']';
--set @count = execute @query
EXEC sp_executesql @query,
N'@count int OUTPUT',
@count = @count OUTPUT
update @tempTbl set RecordCount = @count where TableName = @tName
print @query
fetch next from curCount into @tName
end
close curCount
deallocate curCount
答案 1 :(得分:0)
仅当我在select语句中也添加了变量时才为我工作。替换为:
set @query = N'select count(ID) from ['+@tName+']';
有了这个:
set @query = N'select @count=count(ID) from ['+@tName+']';