2016-08-03 41 views
0

我有一个要求,我必须找出每个表名称已列在主表中的记录数。执行计数内游标,sql server

主表的样子: 的recordId,表名,行数 最初所有行的行数设置为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 ['[email protected]+']'; 
    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'附近的错误语法。

请帮我解决这个问题。

+1

见http://stackoverflow.com/questions/803211/how-to-get-sp-executesql-result-into-a-variable从sp_executesql的 – artm

+0

@Anurag返回结果你可以避免光标获得性能 –

+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 ['[email protected]+']'; 
    --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