次の方法で共有


Visual Basic .NET でトリガを作成、変更、および削除する方法

このセクションでは、Visual Basic .NET を使用してトリガを作成する方法について説明します。

コード例では、AdventureWorks データベースにある "Sales" という名前の既存のテーブル上に、更新トリガを作成および挿入します。トリガによって、テーブルの更新時、または新規レコードの挿入時に通知メッセージが送信されます。

トリガの作成、変更、および削除

  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

  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 mysrv As Server
mysrv = New Server
'Reference the AdventureWorks database.
Dim mydb As Database
mydb = mysrv.Databases("AdventureWorks")
'Declare a Table object variable and reference the Customer table.
Dim mytab As Table
mytab = mydb.Tables("Customer", "Sales")
'Define a Trigger object variable by supplying the parent table, schema ,and name in the constructor.
Dim tr As Trigger
tr = New Trigger(mytab, "Sales")
'Set TextMode property to False, then set other properties to define the trigger.
tr.TextMode = False
tr.Insert = True
tr.Update = True
tr.InsertOrder = Agent.ActivationOrder.First
Dim stmt As String
stmt = " RAISERROR('Notify Customer Relations',16,10) "
tr.TextBody = stmt
tr.ImplementationType = ImplementationType.TransactSql
'Create the trigger on the instance of SQL Server.
tr.Create()
'Remove the trigger.
tr.Drop()

参照

概念

トリガの作成、変更、および削除

ヘルプおよび情報

SQL Server 2005 の参考資料の入手