DEV Community

Query Filter
Query Filter

Posted on

cursor4

set nocount on
go

print 'Tables with data in last 45 days:'
print '==================================================='
print ''

declare @table_name varchar(255)
declare @cnt        int
declare @total      int
declare @sql        varchar(1000)

-- Cursor must be declared after variables, before other statements
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

open table_cursor
fetch next from table_cursor into @table_name

while @@fetch_status = 0
begin
    -- Get count for last 45 days
    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

    -- Only print if there's data
    if @cnt > 0
    begin
        -- Get total count
        select @sql = 'select @total_out = count(*) from ' + @table_name
        execute sp_executesql @sql, N'@total_out int output', @total_out = @total output

        print rtrim(@table_name) + space(40 - len(rtrim(@table_name))) + 
              'Recent: ' + rtrim(convert(varchar(20), @cnt)) + 
              ' / Total: ' + rtrim(convert(varchar(20), @total)) +
              ' (' + rtrim(convert(varchar(10), 
                    convert(numeric(5,1), 
                    case when @total > 0 then (@cnt * 100.0) / @total else 0 end))) + '%)'
    end

    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)