DEV Community

Query Filter
Query Filter

Posted on

cursor5

set nocount on

-- ALL variable declarations FIRST
declare @table_name varchar(255)
declare @cnt        int
declare @sql        varchar(1000)

-- Cursor declaration IMMEDIATELY after variables
declare table_cursor cursor for
    select o.name
    from sysobjects o
    where o.type = 'U'
      and exists (select 1 from syscolumns c 
                  where c.id = o.id and c.name = 'INTERNTIMESTAMP')
    order by o.name

-- Now the rest of the code
print 'TABLE_NAME                             ROWS_LAST_45_DAYS'
print '-------------------------------------------------------------'

open table_cursor
fetch next from table_cursor into @table_name

while @@fetch_status = 0
begin
    select @sql = 'select @cnt_out = count(*) from ' + @table_name +
                  ' where INTERNTIMESTAMP >= dateadd(day, -45, getdate())'

    execute sp_executesql @sql, N'@cnt_out int output', @cnt_out = @cnt output

    print rtrim(@table_name) + replicate(' ', 38 - len(rtrim(@table_name))) + 
          convert(varchar(20), isnull(@cnt,0))

    fetch next from table_cursor into @table_name
end

close table_cursor
deallocate table_cursor
go
Enter fullscreen mode Exit fullscreen mode

Top comments (0)