Visual Basic .NET でスキーマを作成、変更、および削除する方法

このセクションでは、Microsoft Visual Basic .NET を使用して、スキーマを作成し、それをデータベース オブジェクトおよびユーザーに割り当てる方法について説明します。

コード例では、スキーマを作成して、ユーザーに権限を許可し、そのスキーマに新しいテーブルを作成する方法を示します。

スキーマの作成および削除

  1. Visual Studio 2005 を起動します。

  2. [ファイル] メニューの [新規作成] をポイントして [プロジェクト] をクリックします。[新しいプロジェクト] ダイアログ ボックスが表示されます。

  3. [プロジェクトの種類] ペインで、[Visual Basic] をクリックします。[テンプレート] ペインで、[コンソール アプリケーション] をクリックします。

  4. (省略可) [名前] ボックスに新しいアプリケーションの名前を入力します。

  5. [OK] をクリックすると、Visual Basic コンソール アプリケーション テンプレートが読み込まれます。

  6. [プロジェクト] メニューの [参照の追加] をクリックします。[参照の追加] ダイアログ ボックスが表示されます。[参照] をクリックして、C:\Program Files\Microsoft SQL Server\90\SDK\Assemblies フォルダ内で SMO アセンブリを探します。次のファイルを選択します。

    Microsoft.SqlServer.ConnectionInfo.dll

    Microsoft.SqlServer.Smo.dll

    Microsoft.SqlServer.SqlEnum.dll

    Microsoft.SqlServer.SmoEnum.dll

  7. [表示] メニューの [コード] をクリックします。または、[Module1.vb] ウィンドウをクリックしてコード ウィンドウを表示します。

  8. コードでは、宣言の前に、次の Imports ステートメントを入力し、SMO 名前空間の型を修飾します。

    Imports Microsoft.SqlServer.Management.Smo
    Imports Microsoft.SqlServer.Management.Common
    
  9. このプロシージャの後に続くコードをメイン プログラムに挿入します。

  10. アプリケーションを実行およびビルドします。

使用例

'Connect to the local, default instance of SQL Server.
Dim srv As Server
srv = New Server
'Reference the AdventureWorks database.
Dim db As Database
db = srv.Databases("AdventureWorks")
'Define a Schema object variable by supplying the parent database and name arguments in the constructor.
Dim sch As Schema
sch = New Schema(db, "MySchema1")
sch.Owner = "dbo"
'Create the schema on the instance of SQL Server.
sch.Create()
'Define an ObjectPermissionSet that contains the Update and Select object permissions.
Dim obperset As ObjectPermissionSet
obperset = New ObjectPermissionSet()
obperset.Add(ObjectPermission.Select)
obperset.Add(ObjectPermission.Update)
'Grant the set of permissions on the schema to the guest account.
sch.Grant(obperset, "guest")
'Define a Table object variable by supplying the parent database, name and schema arguments in the constructor.
Dim tb As Table
tb = New Table(db, "MyTable", "MySchema1")
Dim mycol As Column
mycol = New Column(tb, "Date", DataType.DateTime)
tb.Columns.Add(mycol)
tb.Create()
'Modify the owner of the schema and run the Alter method to make the change on the instance of SQL Server.
sch.Owner = "guest"
sch.Alter()
'Run the Drop method for the table and the schema to remove them.
tb.Drop()
sch.Drop()

参照

概念

スキーマの作成、変更、および削除

その他の技術情報

ユーザーとスキーマの分離

ヘルプおよび情報

SQL Server 2005 の参考資料の入手