创建、更改和删除数据库

适用于:SQL ServerAzure SQL 数据库Azure 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