Constraint (Constraint) is a method provided by Microsoft SQL Server to automatically maintain database integrity by defining restrictions on the data that can be entered into a single column of a table or table (for an Introduction to data integrity, see chap. 9th). There are 5 kinds of constraints in SQL Server: PRIMARY KEY constraint (Primary key Constraint), foreign keyword constraint (Foreign key Constraint), uniqueness constraint (unique Constraint), check constraints Constraint) and the default constraint (defaulted Constraint).
7.2.1 PRIMARY keyword Constraint
A PRIMARY KEY constraint specifies that the value of a combination of one or more columns of a table is unique in the table, that is, a single row of records can be specified uniquely. Only one column in each table can be specified as the primary key, and columns of image and text types cannot be specified as primary, or null attributes are not allowed for the specified primary key column.
The syntax for defining a PRIMARY keyword constraint is as follows:
CONSTRAINT constraint_name
PRIMARY KEY [CLUSTERED | Nonclustered]
(column_name1[, column_name2,..., Column_name16])
The parameters are described as follows:
Constraint_name
Specifies the name of the constraint's name constraint. Should be unique in the database. If not specified, a constraint name is automatically generated. CLUSTERED | Nonclustered
Specifies the index category, CLUSTERED the default value. For specific information, see the next chapter. column_name
Specifies the name of the column that makes up the primary key. The primary keyword consists of up to 16 columns.
Example 7-3: Create a Product information table with the product number and name as the primary keyword
CREATE TABLE Products (
p_id Char (8) NOT NULL,
P_name Char (TEN) NOT NULL,
Price Money default 0.01,
Quantity smallint NULL,
Constraint pk_p_id primary KEY (p_id, P_name)
) on [primary]
7.2.2 external keyword Constraint
An external keyword constraint defines a relationship between tables. When a table has a column or combination of columns and a primary keyword definition in another table, you can define a combination of those columns or columns as an external keyword and set which columns are associated with which table. In this way, when the column value is updated in the table that defines the primary KEY constraint, the foreign key column in the other table with the Foreign keyword constraint associated with it will be updated accordingly. The external keyword constraint also shows that when inserting data into a table with an external keyword, the system rejects inserting data if the table associated with it does not have the same value as the inserted external key column value. As with the primary key, you cannot create an external keyword using a column defined as the TEXT or image data type. The foreign keyword is composed of up to 16 columns.