SQL Server – Changing the ‘Default Database’ Option in Login

loginssql serversql-server-2012

I am looking for a way to change the option of "default database" to master for all the logins on my instance from current user database in order to maintain the consistency.

Application code logins are all set to use " USE [DBNAME]" so changing all logins to master should be good.

Is there a way to have the script check first or list all logins with default databases and then listing/printing the changes to change the above?

Thanks

Best Answer

You can use sys.server_principals to find default database and alter login to change it.

SELECT name,
       default_database_name,
       'alter login ['+name+'] with default_database=master;'
FROM sys.server_principals
WHERE default_database_name <> 'master';