DEV Community

Query Filter
Query Filter

Posted on

cursor3

set nocount on
###

print 'TABLE_NAME                             ROWS_LAST_45_DAYS'
print '-------------------------------------------------------------'
###

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

    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
        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
END
###
Enter fullscreen mode Exit fullscreen mode

Top comments (0)