SQL Server(第一章) 创建表 删除表 创建主键约束、唯一约束、外键约束、CHECK约束、默认约束


1.Employees员工表
/**
创建Employees员工表
**/
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
)
/**
添加主键约束
**/
ALTER TABLE dbo.Employees ADD CONSTRAINT PK_Employees
PRIMARY KEY(empid);
/**
添加唯一约束
**/
ALTER TABLE dbo.Employees ADD CONSTRAINT UNQ_Employees_ssn
UNIQUE(ssn);
/**
添加外键约束
**/
ALTER TABLE dbo.Employees ADD CONSTRAINT FK_Employees_Employees
FOREIGN KEY(mgrid) REFERENCES dbo.Employees(empid);
/**
添加CHECK约束
**/
ALTER TABLE dbo.Employees ADD CONSTRAINT CHK_Employees_salary
CHECK(salary>0.00)
/**
删除CHECK约束
**/
ALTER TABLE dbo.Employees DROP CONSTRAINT CHK_Employees_salary

 

2.Orders订单表

/**
    创建Orders订单表
**/
USE TSQL2012

IF OBJECT_ID('dbo.Orders','U') IS NOT NULL DROP TABLE dbo.Orders;

CREATE TABLE dbo.Orders
(
    orderid    INT    NOT NULL,
    empid    INT NOT NULL,
    custid    VARCHAR(10) NOT NULL,
    orderts    DATETIME2    NOT NULL,
    qty    INT    NOT NULL,
    CONSTRAINT PK_Orders PRIMARY KEY(orderid)
);
/**
添加主键约束
**/
ALTER TABLE dbo.Orders ADD CONSTRAINT FK_Orders_Employees FOREIGN KEY(empid)
REFERENCES dbo.Employees(empid);
/**
添加默认约束
**/
ALTER TABLE dbo.Orders ADD CONSTRAINT DFT_Orders_orderts
DEFAULT(SYSDATETIME()) FOR orderts;

/**
删除CHECK约束
**/
ALTER TABLE dbo.Employees DROP CONSTRAINT DFT_Orders_orderts

 

纯属个人笔记,如有问题大家可以一起沟通。

posted @ 2018-01-01 20:36  渴死的鱼0521  阅读(1652)  评论(0编辑  收藏  举报