How do I set the default database in Sql Server from code?

Brian picture Brian · Sep 19, 2008 · Viewed 21.2k times · Source

I can't seem to figure out how to set the default database in Sql Server from code. This can be either .Net code or T-Sql (T-Sql would be nice since it would be easy to use in any language). I searched Google and could only find how to do it in Sql Server Management Studio.

Answer

Tim picture Tim · Sep 20, 2008

ALTER LOGIN should be used for SQL Server 2005 or later:

http://technet.microsoft.com/en-us/library/ms189828.aspx

ALTER LOGIN <login_name> WITH DEFAULT_DATABASE = <default_database>

sp_defaultdb eventually will be removed from SQL Server:

http://technet.microsoft.com/en-us/library/ms181738.aspx