问题
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