Please can I get help with using T-SQL to loop through all user databases in a SQL server instance

All we need is an easy explanation of the problem, so here it is.

Please can anyone help me with how to loop through all the User databases in an instance executing the below query for each one of them?

The script returns a list of users with their individual permissions in a separate statement.

SELECT 'USE '+ DB_NAME()+'; '+CASE WHEN dp.state <> 'W' THEN dp.state_desc ELSE 'GRANT' END +' ' + 
        dp.permission_name + ' TO ' + QUOTENAME( COLLATE database_default + 
        CASE WHEN dp.state <> 'W' THEN '' ELSE ' WITH GRANT OPTION' END +';' AS [-- Permission To Be Assign to the User --]
FROM    sys.database_permissions AS dp
INNER JOIN sys.database_principals AS dpg ON dp.grantee_principal_id = dpg.principal_id
WHERE   dp.major_id = 0 AND dpg.principal_id > 4
        AND (dpg.type in ('S','G','U'))
        AND NOT LIKE '##%##'
        AND <> ('sa')
        AND dpg.default_schema_name IS NOT NULL
        AND <> 'distributor_admin'
        AND dpg.principal_id > 4

Thank you

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Have a look at Aaron Bertrand’s excellent sp_foreachdb – and he also has a very useful partner sp_ineachdb which may be more what you’re looking for here.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply