Use SMO to Change SQL Server Database Default Locations

此生再无相见时 提交于 2019-12-10 15:33:37

问题


I am using the following code to change the server database default locations (where the SQL Server keeps new database files and log files):

using Microsoft.SqlServer.Management.Smo;

Server smoServer = new Server(new ServerConnection(server, username, password));
server.DefaultFile = newPath;
server.Alter();
server.Refresh();

// Now create a database in the new location
Database smoDatabase = new Database(smoServer, database);
smoDatabase.Create();
smoServer.Refresh();

Here's my problem: I can look in SQL Server Management Studio and see the server property for Database Default Locations has been changed to the newPath. However, when I use SMO to create a new database, the new database and logfile are created in the old path.

Once I restart the SQL Server instance, the SMO code creates the database/logfile in the new path.

Any ideas why I'm getting this behavior?

Edit: One suggestion is that the change doesn't actually take place until the Sql Server Instance is restarted. However, if I open up SSMS and create a new database on the instance, it gets created in the new path without having to restart.


回答1:


You need to add information about Data and Log files explicitly:

// Now create a database in the new location
Database smoDatabase = new Database(smoServer, database);

FileGroup fg = new FileGroup(smoDatabase, "PRIMARY");
DataFile df = new DataFile(fg, "File1", @"c:\sql\file1.mdf");
LogFile lf = new LogFile(smoDatabase, "Log01", @"c:\sql\Log1.ldf");


smoDatabase.Create();
smoServer.Refresh();


来源:https://stackoverflow.com/questions/4331095/use-smo-to-change-sql-server-database-default-locations

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