2016-08-03 75 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