【例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