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

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.

  • Programatically Determine Master Server in SQL Failover Scenario
  • Opening a binary stream (such as a PDF) in the browser
  • Need help to restore multiple databases/bak files from one folder
  • how to query SQL Server via REST to get XML
  • Pivot and concatenate values from column in SQL Server
  • incorrect syntax near the keyword 'Select'. for a balancecode
  • SMO and Sql Server 7.0
  • R forecast output to SQL Server
  • How to find SQL Server running port when you don't own the server?
  • Query that returns multiple result sets
  • What should be the best way to store a percent value in SQL-Server?
  • SQLServer: How to sort table names ordered by their foreign key dependency
  • 4 Solutions collect form web for “How do I set the default database in Sql Server from code?”


    sp_defaultdb [@loginame =] 'login' , [@defdb =] 'database'

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

    ALTER LOGIN <login_name> WITH DEFAULT_DATABASE = <default_database>

    sp_defaultdb eventually will be removed from SQL Server:

    Thanks Stephen.

    As a note, if you are using Windows Authentication, the @loginname is YourDomain\YourLogin (probably obvious to everybody else, but took me a couple tries.

    sp_defaultdb @loginame='YourDomain\YourLogin', @defdb='YourDatabase'

    If you’re trying to change which database you are using after you are logged in, you can use the USE command. E.g. USE Northwind.

    MS SQL Server is a Microsoft SQL Database product, include sql server standard, sql server management studio, sql server express and so on.