共用方式為


建立、改變和移除資料庫

在 SMO 中,資料庫是由 Database 物件表示。

您不必建立 Database 物件,即可修改或移除該物件。您可以利用集合來參考資料庫。

範例

如果要使用所提供的任何程式碼範例,您必須選擇建立應用程式用的程式設計環境、程式設計範本及程式設計語言。如需詳細資訊,請參閱<如何:在 Visual Studio .NET 中建立 Visual Basic SMO 專案>或<如何:在 Visual Studio .NET 中建立 Visual C# SMO 專案>。

在 Visual Basic 中建立、改變和移除資料庫

此程式碼範例會建立新資料庫,並自動為資料庫建立檔案和檔案群組。

'Connect to the local, default instance of SQL Server.
Dim srv As Server
srv = New Server
'Define a Database object variable by supplying the server and the database name arguments in the constructor.
Dim db As Database
db = New Database(srv, "Test_SMO_Database")
'Create the database on the instance of SQL Server.
db.Create()
'Reference the database and display the date when it was created.
db = srv.Databases("Test_SMO_Database")
Console.WriteLine(db.CreateDate)
'Remove the database.
db.Drop()

在 Visual C# 中建立、改變和移除資料庫

此程式碼範例會建立新資料庫,並自動為資料庫建立檔案和檔案群組。

{
                //Connect to the local, default instance of SQL Server. 
                Server srv;
                srv = new Server();
                //Define a Database object variable by supplying the server and the database name arguments in the constructor. 
                Database db;
                db = new Database(srv, "Test_SMO_Database");
                //Create the database on the instance of SQL Server. 
                db.Create();
                //Reference the database and display the date when it was created. 
                db = srv.Databases["Test_SMO_Database"];
                Console.WriteLine(db.CreateDate);
                //Remove the database. 
                db.Drop();
            }

在 PowerShell 中建立、改變和移除資料庫

此程式碼範例會建立新資料庫,並自動為資料庫建立檔案和檔案群組。

#Get a server object which corresponds to the default instance
cd \sql\localhost\
$srv = get-item default

#Create a new database
$db = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Database -argumentlist $srv, "Test_SMO_Database"
$db.Create()

#Reference the database and display the date when it was created. 
$db = $srv.Databases["Test_SMO_Database"]
$db.CreateDate

#Drop the database
$db.Drop()

請參閱

參考