第一章 T-SQL 查询和编程基础

T-SQL Codes:

use XUFEIDB

if object_id('dbo.Orders', 'U') is not null

drop table dbo.orders

if object_id('dbo.Employees', 'U') is not null

drop table dbo.Employees;

--create table

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

);

--add primary key

alter table dbo.employees

add constraint PK_Empid

primary key(empid);

--add unique constraint

alter table dbo.employees

add constraint UK_Ssn

unique(ssn);

--create table

create table dbo.Orders

(

OrderId int not null,

empid int not null,

custid varchar(30) not null,

orderts datetime not null,

qty int not null,

--define primary key

constraint PK_OrderId

primary key(OrderId)

);

--add foreign key

alter table dbo.orders

add constraint FK_Employees_Orders

foreign key(empid)

references dbo.employees(empid);

--add foreign key for one table

alter table dbo.employees

add constraint FK_Employees_Employees

foreign key(mgrid)

references employees(empid);

--add check constraint

alter table dbo.employees

add constraint CHK_Employees_Salary

check(salary>0)

--add default constraint

alter table dbo.orders

add constraint DFT_Orders_orderts

default(current_timestamp) for orderts

你可能感兴趣的:(t-sql)