외래 키 생성, 변경 및 제거

SQL Server Management Objects(SMO)에서 외래 키는 ForeignKey 개체로 표시됩니다.

SMO에서 외래 키를 만들려면 ForeignKey 개체의 생성자에 외래 키가 정의되는 테이블을 지정해야 합니다. 이 테이블에서 외래 키가 될 열을 적어도 하나 이상 선택해야 합니다. 이를 위해 ForeignKeyColumn 개체 변수를 만들고 외래 키 열의 이름을 지정합니다. 그런 다음 참조되는 테이블과 참조되는 열을 지정합니다. Add 메서드를 사용하여 Columns 개체 속성에 열을 추가합니다.

외래 키를 나타내는 열이 ForeignKey 개체의 Columns 개체 속성에 나열됩니다. 외래 키에서 참조되는 기본 키는 ReferencedTable 속성에 지정된 테이블에 있는 ReferencedKey 속성으로 표시됩니다.

제공된 코드 예제를 사용하려면 응용 프로그램을 만들 프로그래밍 환경, 프로그래밍 템플릿 및 프로그래밍 언어를 선택해야 합니다. 자세한 내용은 방법: Visual Studio .NET에서 Visual Basic SMO 프로젝트 만들기 또는 방법: Visual Studio .NET에서 Visual C# SMO 프로젝트 만들기를 참조하십시오.

Visual Basic에서 외래 키 생성, 변경 및 제거

이 코드 예제는 한 테이블의 하나 이상의 열 사이에서 다른 테이블의 기본 키 열에 대한 외래 키 관계를 만드는 방법을 보여 줍니다.

'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()

Visual C#에서 외래 키 생성, 변경 및 제거

이 코드 예제는 한 테이블의 하나 이상의 열 사이에서 다른 테이블의 기본 키 열에 대한 외래 키 관계를 만드는 방법을 보여 줍니다.

{ 
//Connect to the local, default instance of SQL Server. 
Server srv; 
srv = new Server(); 
//Reference the AdventureWorks database. 
Database db; 
db = srv.Databases("AdventureWorks"); 
//Declare a Table object variable and reference the Employee table. 
Table tbe; 
tbe = db.Tables("Employee", "HumanResources"); 
//Declare another Table object variable and reference the EmployeeAddress table. 
Table tbea; 
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. 
ForeignKey fk; 
fk = new ForeignKey(tbea, "test_foreignkey"); 
//Add EmployeeID as the foreign key column. 
ForeignKeyColumn fkc; 
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();
}