【例3.1】 为用户WANG定义一个学生-课程模式S-T:
在定义之前首先检查数据库中是否存在WANG。如果没有,需先创建该用户。
create schema "S-T" authorization WANG;
authorization为授权,schema为架构。
【例3.2】该语句没有指定<模式名>,<模式名>隐含为<用户名>
在没有创建模式的情况下,默认的模式名为dbo,表名为dbo.*。
create schema authorization WANG;
【例3.3】为用户WANG创建了一个模式TEST,并且在其中定义一个表TAB1:
create schema TEST authorization WANG
create table TAB1(col1 smallint,
col2 int,
col3 char(20),
col4 numeric(10,3),
col5 decimal(5,2),
);
TEST模式建立成功,继续在TEST模式下建立表TAB2:
若建表时未指明模式,则表均在模式模式dbo下建立:
【例3.4】DROP SCHEMA TEST CASCADE;
DROP SCHEMA TEST CASCADE;
注意:以上代码会出现语法错误,因为SQL Server不支持在DROP SCHEMA使用CASCADE。需要下删除该模式下的所有子表,然后再删除该模式。
drop table TEST.TAB1
drop table TEST.TAB2
drop schema TEST
【例3.5】建立一个“学生”表Student。学号是主码,姓名取唯一值。
create table student(
sno char(9) primary key,
sname char(20) unique,
ssex char(2),
sage smallint,
sdept char(20)
);
【例3.6】建立一个“课程”表Course。
create table course(
cno char(4) primary key,
cname char(40),
cpno char(4),
ccredit smallint,
foreign key (cpno) references course(cno)
);
【例3.7】建立学生选课表SC。
create table sc(
sno char(9),
cno char(4),
grade smallint,
primary key(sno,cno),
foreign key (sno) references student(sno),
foreign key (cno) references course(cno)
);
【例3.8】向Student表增加“入学时间”列,其数据类型为日期型。
alter table student add s_entertime date
【例3.9】将年龄的数据类型由字符型(假设原来的数据类型是字符型)改为整数。
alter table student alter column sage int
【例3.10】增加课程名称必须取唯一值的约束条件。
alter table course add unique(cname)
【例3.11】删除Student表。
drop table student
因为上面我们已经讨论过在SQL Server中不支持使用CASCADE,不然会报错。除此之外,上面student在建立表SC时,用了student表的Sno做外码,有约束,所以不能删除。因此需要删除SC后,Student才可以删除成功。
drop table sc
drop table student
【例3.12】若表上建有视图,使用RESTRICT时表不能删除;使用CASCADE时可以删除表,视图也自动删除。
create view is_student
as
select sno,sname,sage
from student
where sdept='is'
首先我们创建基于Student的视图IS_Student:
使用restrict删除时,由于表下有视图,会出现语法错误:
因此我们要先删除is_student视图,再删除student:
由于我上面没有删除sc,所以现在报错。因此只需要在语句中间加上删除sc便可成功删除(应该一步到位,若经过上面报错,需要把第一行代码删去):
drop view is_student
drop table sc
drop table student