declare db_c cursor for select [name] from sys.database...

0

Please login or register to vote for this query.

(click on this box to dismiss)

Code Review

Q&A for peer programmer code reviews

--select count(id), avg(upvotes), avg(downvotes), sum(upvotes), sum(downvotes)
--from users where reputation>=150

declare  db_c cursor for select [name] 
       from sys.databases 
       where database_id > 5 -- skip master, temp, model, msdb, Data.SE

declare @db_c_name sysname   -- holds name of db after fetch
declare @sql nvarchar(max) -- holds build up sql string

-- result table
create table #all_users (
    name nvarchar(40)
    , users int
    , avgUp int
    , avgDn int
    , totalUp int
    , totalDown int
    --,
);

open db_c
fetch next from db_c into @db_c_name
while(@@FETCH_STATUS = 0)
begin
    set @sql = N'use '+ QUOTENAME(@db_c_name) +';
    insert into #all_users 
    select
    '''+ 
       QUOTENAME(@db_c_name) +
    '''
    ,count(id), avg(upvotes), avg(downvotes), sum(upvotes), sum(downvotes) 
    from users
    ';
    exec (@sql)
   fetch next from db_c into @db_c_name
end;
close db_c;
deallocate db_c;

select * from #all_users

Enter Parameters

Options:
Switch sites:
loading Hold tight while we fetch your results