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

このセクションでは、Visual Basic .NET で外部キーを作成、変更、および削除する方法について説明します。

コード例では、あるテーブル内の 1 つまたは複数の列から、別のテーブル内の主キー列に対する外部キー リレーションシップを作成する方法を示します。

外部キーの作成、変更、および削除

  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")
'Declare a Table object variable and reference the Employee table.
Dim tbe As Table
tbe = db.Tables("Employee", "HumanResources")
'Declare another Table object variable and reference the EmployeeAddress table.
Dim tbea As Table
tbea = db.Tables("EmployeeAddress", "HumanResources")
'Define a Foreign Key object variable by supplying the EmployeeAddress as the parent table and the foreign key name in the constructor.
Dim fk As ForeignKey
fk = New ForeignKey(tbea, "test_foreignkey")
'Add EmployeeID as the foreign key column.
Dim fkc As ForeignKeyColumn
fkc = New ForeignKeyColumn(fk, "EmployeeID", "EmployeeID")
fk.Columns.Add(fkc)
'Set the referenced table and schema.
fk.ReferencedTable = "Employee"
fk.ReferencedTableSchema = "HumanResources"
'Create the foreign key on the instance of SQL Server.
fk.Create()

参照

概念

外部キーの作成、変更、および削除

ヘルプおよび情報

SQL Server 2005 の参考資料の入手