0

I have a requirement where i have to find out the number of records for each table names which are already listed in a master table.

the master table looks like: RecordId, TableName, RowCount initially all the rows for RowCOunt set to 0.

what i did was, created a cursor

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

it gives me error every time at this point set @count = execute @query, error is: Incorrect syntax near the keyword 'exec'.

i have tried sp_executesql @query as well... it also gives me error, error is Incorrect syntax near '@query'.

Please help me to fix this.

AChauhan
  • 207
  • 3
  • 15

2 Answers2

0

You can use sp_executesql with an output parameter to get the value . Please try this :

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
Bhavika Zimbar
  • 411
  • 1
  • 5
  • 19
0

worked for me only when I added the variable in the select statement as well. Replace this: set @query = N'select count(ID) from ['+@tName+']'; with this: set @query = N'select @count=count(ID) from ['+@tName+']';

spambo01
  • 31
  • 8