Recently I noticed in my daily work that every time I logged in MS SQL I was required to select the database which I had to work on and this was regularly in use by me and this lead me to find the solution to change the default database selection after I log on to MS SQL using SSMS to reduce the hassle and also so that I don’t execute queries on different databases by mistake.
Exec sp_defaultdb @loginame='Domain/UserName', @defdb='MyDefaultDatabaseName'
Here value of parameter @loginname is User Name such as ‘sa’ and it can change depending on the MSSQL login configurations such as Sql Authentication or Windows Authentication. Example shown here is for Windows Authentication. Then value of parameter @defdb is the database name such as ‘master’ or ‘AdventureWorks’ and it will change as per the need to set the default database for the particular login specified.
But this stored procedure seems soon to be obsolete as mentioned in MSDN link here. There is newer option available for this purpose – ALTER LOGIN which has many other usability apart from setting the default database but I would stick to the topic and show its usage.
ALTER LOGIN [Domain\UserName] WITH DEFAULT_DATABASE = [MyDefaultDatabaseName]
I hope you found this helpful and learnt something new from this.
Keep your comments flowing for what you prefer. 🙂