建立、改變和移除資料庫

適用於:SQL ServerAzure SQL DatabaseAzure SQL 受控執行個體Azure Synapse Analytics

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

不需要建立 Database 物件來修改或移除它。 您可以使用集合來參考資料庫。

範例

若要使用提供的任何程式碼範例,您必須選擇程式設計環境、程式設計範本,以及用來建立應用程式的程式設計語言。 如需詳細資訊,請參閱 在 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()  

另請參閱

Database