This section describes how to create, alter, and remove a foreign key in Visual Basic .NET.
The code example shows how to create a foreign key relationship between one or more columns in one table to a primary key column in another table.
Creating, altering, and removing foreign keys
- Start Visual Studio 2005. 
- From the File menu, select New Project. The New Project dialog box appears. 
- In the Project Types pane, select Visual Basic. In the Templates pane, select Console Application. 
- (Optional) In the Name box, type the name of the new application. 
- Click OK to load the Visual Basic console application template. 
- On the Project menu, select Add Reference item. The Add Reference dialog box appears. Select Browse and locate the SMO assemblies in the C:\Program Files\Microsoft SQL Server\90\SDK\Assemblies folder. Select the following files: - Microsoft.SqlServer.ConnectionInfo.dll - Microsoft.SqlServer.Smo.dll - Microsoft.SqlServer.SqlEnum.dll - Microsoft.SqlServer.SmoEnum.dll 
- On the View menu, click Code.-Or-Select the Module1.vb window to display the code window. 
- In the code, before any declarations, type the following Imports statements to qualify the types in the SMO namespace: - Imports Microsoft.SqlServer.Management.Smo Imports Microsoft.SqlServer.Management.Common
- Insert the code that follows this procedure into the main program. 
- Run and build the application. 
示例
'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()
请参阅
概念
Creating, Altering, and Removing Foreign Keys