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

杀马特。学长 韩版系。学妹 提交于 2019-11-27 03:54:13

问题


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.


回答1:


from: http://doc.ddart.net/mssql/sql70/sp_da-di_6.htm

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



回答2:


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




回答3:


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'



回答4:


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.

https://www.tutorialspoint.com/sql/sql-select-database.htm



来源:https://stackoverflow.com/questions/105950/how-do-i-set-the-default-database-in-sql-server-from-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!