1、創建表
use TSQL2012;
if object_id('dbo.Employees','U') is not null
drop table dbo.Employees;
create table dbo.Employees
(
empid int not null,
firstname varchar(30) not null,
lastname varchar(30) not null,
hiredate date not null,
mgrid int null,
ssn varchar(20) not null,
salary money not null
);
2、添加主鍵約束
alter table dbo.Employees
add constraint PK_Employees
primary key(empid);
3、添加唯一約束
alter table dbo.Employees
add constraint UNQ_Employees_ssn
UNIQUE(ssn);
4、添加外鍵約束
在Orders表的empid列上定義一個外鍵約束,指向Employees表中的empid列。
alter table dbo.Orders
add constraint FK_Orders_Employees
foreign key(empid)
references dbo.Employees(empid);
5、添加CHECK約束
alter table dbo.Employees
add constraint CHK_Employees_salary
CHECK(salary >0.00);
4、添加默認約束
爲orderts屬性定義默認約束(即訂單的時間戳)
alter table dbo.Orders
add constraint DFT_Orders_orderts
default(sysdatetime()) for orderts;