Loop through all databases

  • How can I run this code to loop through all databases and just not one at a time?

    declare @group1 varchar (500), @group2 varchar (500)

    select @group1 = 'domain\SQLAccess_System_Administration'

    select @group2 = 'domain\SQLAccess_System_Administration'

    if OBJECT_ID ('tempdb.dbo.#tmpUserPerm') is not null

    drop table #tmpUserPerm

    if OBJECT_ID ('tempdb.dbo.#TmpUser') is not null

    drop table #TmpUser

    if OBJECT_ID ('tempdb.dbo.#tmpUserPerm') is not null

    drop table #tmpUserPerm

    Create table #tmpUserPerm

    (UserName varchar(100),

    GroupName varchar(100),

    LoginName varchar(100),

    DefDBName varchar(100),

    UserId int,

    SID varbinary(100),

    DefSchemaName varchar(100) null)

    Declare @name varchar(100)

    select uid, name into #TmpUser from sysusers

    --where issqluser = 1

    where hasdbaccess <> 0 and name = @group1

    declare cur Cursor for Select name from #Tmpuser

    open cur

    fetch next from cur into @name

    while @@fetch_Status = 0

    BEGIN

    insert into #tmpUserPerm (UserName, GroupName, LoginName, DefDBName, DefSchemaName, UserId, SID)

    Exec sp_helpuser @name

    fetch next from cur into @name

    END

    close cur

    deallocate cur

    select @group2, UserName, groupname, loginname, defdbname, userid from #tmpUserPerm order by 1

  • This article on an undocumented procedure might assist you

    http://www.sqlservercentral.com/articles/Advanced+Querying/sp_msforeachdb/182/

    If everything seems to be going well, you have obviously overlooked something.

    Ron

    Please help us, help you -before posting a question please read[/url]
    Before posting a performance problem please read[/url]

  • Here is another method

    http://spaghettidba.com/2011/09/09/a-better-sp_msforeachdb/

    Jason...AKA CirqueDeSQLeil
    _______________________________________________
    I have given a name to my pain...MCM SQL Server, MVP
    SQL RNNR
    Posting Performance Based Questions - Gail Shaw[/url]
    Learn Extended Events

  • Thank you for the replies.

Viewing 4 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply