数据定义功能
定义基本表
CREATE TABLE Student(Sno char(7) PRIMARY KEY,Sname char(10) NOT NULL,Ssex char(2),Sage tinyint,--年龄,微整型Sdept char(20),--所在系
)CREATE TABLE Course(Cno char(6) NOT NULL,Cname char(20) NOT NULL,Credit tinyint,Semester tinyint,--学期,微整型PRTMARY KEY(Cno)
)CREATE TABLE SC(Sno char(7) NOT NULL,Cno char(6) NOT NULL,Grade smallint,--小整型PRIMARY KEY(Sno,Cno),FOREIGN KEY(Sno) REFERENCES Student(Sno),FOREIGN KEY(Cno) REFERENCES Course(Cno)
)
删除表
DROP TABLE Student
修改表结构
ALTER TABLE <表名>ADD <列名> <数据类型> <约束>--添加列DROP COLUMN <列名>--删除列ALTER COLUMN <列名> <新数据类型>--修改列定义ADD CONSTRAINT--添加约束DROP CONSTRAINT--删除约束ALTER TABLE StudentADD Spec char(10) NULL--添加专业列ALTER TABLE StudentALTER COLUMN Spec char(20)--修改专业列定义ALTER TABLE StudentDROP COLUMN Spec
数据完整性
主码约束
ALTER TABLE EmployeeADD CONSTRAINT PK_EMP PRIMARY KEY(Eid)
ALTER TABLE JobADD CONSTRAINT PK_JOB PRIMARY KEY(Jid)
UNIQUE约束
ALTER TABLE EmployeeADD CONSTRAINT UQ_Eid UNIQUE(Tel)
外码约束
ALTER TABLE EmployeeADD CONSTRAINT FK_Jid FOREIGN KEY (Jid) REFERENCES Job(Jid)
DEFAULT约束
ALTER TABLE EmployeeADD CONSTRAINT DF_Saraly DEFAULT 1600 FOR Saraly--默认值
CHECK约束
ALTER TABLE EmployeeADD CONSTRAINT CHK_Salary CHECK (Salary>1000)
ALTER TABLE EmployeeADD CONSTRAINT CHK_Salary CHECK (Lowest_Salary<=Highest_Salary)
以上约束可以同时定义
CREATE TABLE Job(Jid char(8) PRIMARY KEY,Lowest_Salary int,Highest_Salary int,CHECK(Lowest_Salary<=Highest_Salary)
)
CREATE TABLE Employee(Eid char(7) PRIMARY KEY,Ename char(10),Jid char(8) REFERENCES Job(Jid),Salary int DEFAULT 1600 CHECK(Salary>=1000),Tel char(8) NOT NULL UNIQUE
)