How to use foreign key constraints : Foreign Key « Constraints « SQL Server / T-SQL

SQL Server / T-SQL
1. Aggregate Functions
2. Analytical Functions
3. Constraints
4. Cursor
5. Data Set
6. Data Type
7. Database
8. Date Timezone
9. Index
10. Insert Delete Update
11. Math Functions
12. Select Query
13. Sequence
14. Store Procedure Function
15. String Functions
16. Subquery
17. System
18. Table
19. Table Joins
20. Transact SQL
21. Transaction
22. Trigger
23. View
24. XML
Java
Java Tutorial
Java Source Code / Java Documentation
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
C# / C Sharp
C# / CSharp Tutorial
ASP.Net
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
PHP
Python
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
SQL Server / T-SQL » Constraints » Foreign Key 
How to use foreign key constraints

 


The syntax of a column-level foreign key constraint

[FOREIGN KEYREFERENCES ref_table_name (ref_column_name)
    [ON DELETE {CASCADE|NO ACTION}]
    [ON UPDATE {CASCADE|NO ACTION}]

The syntax of a table-level foreign key constraint

FOREIGN KEY (column_name_1 [, column_name_2]...)
    REFERENCES ref_table_name (ref_column_name_1
[, ref_column_name_2]...)
    [ON DELETE {CASCADE|NO ACTION}]
    [ON UPDATE {CASCADE|NO ACTION}]

A foreign key constraint defined at the column level

A statement that creates the primary key table

28CREATE TABLE Bankers
29(BankerID        INT NOT NULL PRIMARY KEY,
30> BankerName       VARCHAR(50NOT NULL)
31> GO
1>
2> --A statement that creates the foreign key table
3>
4CREATE TABLE Billings
5(BillingID       INT NOT NULL PRIMARY KEY,
6> BankerID         INT NOT NULL REFERENCES Bankers (BankerID),
7> BillingTotal     MONEY NULL)
8> GO
1>
2> --An INSERT statement that fails because a related row doesn't exist
3>
4INSERT Billings VALUES (199100)
5> GO
Msg 547, Level 16, State 1, Server J\SQLEXPRESS, Line 4
The INSERT statement conflicted with the FOREIGN KEY constraint "FK__Billings__Banker__5F9EF494". The conflict occurred in database "master", table "dbo.Bankers", column 'BankerID'.
The statement has been terminated.
1>
2>
3> drop table Billings;
4> drop table Bankers;
5> GO

 
Related examples in the same category
1. Define Primary key and foreign key
2. Table-level constraints
3. Adding a Foreign Key to an Existing Table
www.java2java.com | Contact Us
Copyright 2010 - 2030 Java Source and Support. All rights reserved.
All other trademarks are property of their respective owners.