You are on page 1of 13

Constraints

Microsoft SQL Server allows you to specify constraints of various types on tables, so that the database engine itself can handle various types of validations automatically. Constraints can be specified in two ways: column constraint, or table constraint. A column constraint is linked to specify column in a table, while a table constraint can refer to one or more columns within a table. In a CREATE TABLE statement, a column constraint is specified along with the name of the column that refers to; while a table constraint is given after all the column specifications have been given.

NOT NULL Constraints

A NOT NULL constraint on a column is used to tell the database that a value must always be specified for that column; it cannot be null. For example, create table a ( b char (1) not null) If you want to allow a null value for a column, you must use the NULL clause instead. For example: create table a2 (b char (1) null) The default in SQL Server is NOT NULL.

Primary Key Constraints

A primary key constraint specifies that a field or group of fields in a table should have unique, non-null values. For example, create table dept ( dept_code char (4) primary key, dept_name varchar(10) ) We can also specify a named column constraint for the same purpose, as follows: create table dept ( dept_code char (4) constraint dept_pk primary key, dept_name char (2))

Alternatively, we can specify a named table constraint, as follows: create table dept (dept_code char (4), dept_name char (2), constraint dept_pk primary key (dept_code) )

To view the list of constraints on table, you can give the following command: exec sp_helpconstraint dept

Foreign Key Constraints

SQL Server enforces referential integrity through the use of foreign key constraint. For example, create table dept ( dept_code char (4), dept_name char (2), constraint dept_pk primary key (dept_code) ) create table employee (emp_code number(5), emp_name char (30), dept_code char (4), constraint employee_fk01 foreign key (dept_code) references dept (dept_code))

CREATE DEFAULT

Create default keyword creates an object called default. When bound to a column or a user-defined data type, a default specifies a value to be inserted into the column to which the object is bound (or into all columns, in the case of a user-defined data type) when no value is explicitly supplied during an insert. Syntax : CREATE DEFAULT default AS constant_expression This example creates a character default of unknown CREATE DEFAULT phonedflt AS unknown sp_bindefault phonedflt,authors.phone

CREATE RULE

Creates an object called a rule. When bound to a column or a user-defined data type, a rule specifies the acceptable values that can be inserted into that column.

Syntax : CREATE RULE rule AS condition_expression Example CREATE RULE check_emp_id as @value LIKE '[0-9][0-9][0-9][0-9][0-9][0-9] [0- 9][0-9][0-9]' SP_BINDRULE check_emp_id, empid

You might also like