create table <表名> (<列名><數(shù)據(jù)類型>[列級(jí)完整性約束條件][,<列名><數(shù)據(jù)類型>[列級(jí)完整性約束條件]]….[,<表級(jí)完整性約束條件>])
其中約束條件包括not null —–非空,unique—–唯一(當(dāng)一個(gè)表的其中一個(gè)屬性被設(shè)置為unique時(shí),插入兩個(gè)此屬性相同的記錄時(shí),第二個(gè)插入操作會(huì)被拒絕,以此來(lái)保證此屬性列在各記錄上的分量上唯一),PRimary key——–將一個(gè)屬性列設(shè)置為主碼(primary key等同于 not null + unique)
下面結(jié)合幾個(gè)例子幫助各位看官深入理解一下創(chuàng)建過(guò)程: 例1:創(chuàng)建一個(gè)customer表,包含customer _name(存儲(chǔ)字長(zhǎng)為20個(gè)char長(zhǎng)度),customer _street(存儲(chǔ)字長(zhǎng)為30個(gè)char長(zhǎng)度),customer _city(存儲(chǔ)字長(zhǎng)為30個(gè)char長(zhǎng)度)這三個(gè)屬性列, 其中customer _name為非空,customer _street必須是唯一的,且規(guī)定customer _name是這個(gè)表的主碼 create table customer( customer_name char(20) not null customer_street char(30) unique customer_city char(30), primary key (customer _name));
例2:創(chuàng)建一個(gè)branch表,包括branch_name(存儲(chǔ)字長(zhǎng)為15個(gè)char長(zhǎng)度且為非空),branch _city(存儲(chǔ)字長(zhǎng)為30個(gè)char長(zhǎng)度), assets(小數(shù))三個(gè)屬性列,其中branch _name是主碼 create table branch( branch_name char(15) not null, branch_city char(30), assets decimal, primary key(branch _name), check(assets >=0);) 最后一行語(yǔ)句是檢查約束語(yǔ)句,檢查assets>=0。當(dāng)對(duì)數(shù)據(jù)庫(kù)執(zhí)行插入操作時(shí),如assets這一列輸入的值<0則會(huì)被數(shù)據(jù)庫(kù)報(bào)錯(cuò)以此來(lái)保證assets>=0
例3:創(chuàng)建一個(gè)account表,其中包括account_number(存儲(chǔ)字長(zhǎng)為10個(gè)char長(zhǎng)度且非空且為主碼),branch _name(存儲(chǔ)字長(zhǎng)為15個(gè)char長(zhǎng)度且為外碼,此屬性列在branch表中為主碼),balance(存儲(chǔ)為int且>=0)三個(gè)屬性列 create table account( account_number char(10) not null, branch_name char(15), balance int, primary key(account_number), foreign key(branch_name), reference branch(branch_name), check(balance>=0));
例4:創(chuàng)建一個(gè)deposit表,包括customer_name(存儲(chǔ)字長(zhǎng)為20個(gè)char長(zhǎng)度且非空且為外碼,參照于customer表中的customer _name屬性列),account _number(存儲(chǔ)字長(zhǎng)為10個(gè)char長(zhǎng)度且非空且為外碼,參照于account表中的account _number屬性列)這兩個(gè)屬性列,其中customer _name和account _number共同作為deposit表的主碼 create table deposit( customer_name char(20) not null, account_number char(10) not null, primary key(customer_name,account _number), foreign key(customer_name) reference customer (customer _name), foreign key(account _number) reference account(account _number));
alter table <表名> [add <新列名><數(shù)據(jù)類型>[列級(jí)完整性約束條件]] [drop <列名><完整性約束條件>] [modify <列名><數(shù)據(jù)類型>];
舉例: 如數(shù)據(jù)庫(kù)中覺(jué)得Sage使用int來(lái)存儲(chǔ)太浪費(fèi)了,需要把存儲(chǔ)字長(zhǎng)改小一點(diǎn):alter table Student modify Sage,small int 如需要?jiǎng)h除Sname這一屬性:alter table Student drop Sname 如需要增加Scome Date 這一屬性:alter table Student add Scome Date
drop table <表名> 如:刪除Student表 :drop table Studnent
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注