SQL Server-创建表格、各种约束条件
/*++++++++++++++++|創(chuàng)建表格、各種約束條件|++++++++++++++++++++*/
/*
創(chuàng)建表格P145
CREATE TABLE <表名>
(
???????? <列名><列類型><列說明>…,
???????? [CONSTRAINT <約束名稱><約束條件>]
)
<列類型>是列的數(shù)據(jù)類型。
<列說明>說明列的長度、列的默認值、主鍵等有關(guān)該列的約束條件。
創(chuàng)建主鍵約束 P125
???????? 語法: constraint 主鍵約束名 primary key(被定義為主鍵的列名)
創(chuàng)建外鍵約束 P126
???????? 語法:constratint 外鍵約束名 foreign key(本表中作為外鍵的列名) references 參照表(參照列)
主鍵和外鍵約束,其實就是創(chuàng)建關(guān)系
詳細的內(nèi)容看下面的創(chuàng)建表格的部分說明
??????????????????????????????????????????????????劉峰 編寫 QQ:121497974
*/
--=======================================================
--=下面是分別創(chuàng)建 學(xué)新基本信息表、課程表、職工表、成績表=
--=======================================================
use 學(xué)生信息數(shù)據(jù)庫? --指定使用的數(shù)據(jù)庫,這一步以后不再說明
go
create table 學(xué)生基本信息表
(
???????? 學(xué)號 char(4) not null constraint PK_學(xué)號 primary key, ?
--學(xué)號就是列名,char(4)是列定義的數(shù)據(jù)類型,定義該列的同時可以進行
???????? 性別 char(8) not null default('男') constraint CK_性別 check (性別='男'or 性別='女'),?
--約束定義 constraint 約束名稱 約束內(nèi)容,
???????? 出生日期 datetime not null,
???????? 籍貫 char(10),
???????? 院系名稱 char(20),
???????? 專業(yè) char(20),
???????? 入學(xué)日期 datetime not null,
???????? 獎學(xué)金 money default(0) constraint CK_獎學(xué)金 check (獎學(xué)金>=0 and 獎學(xué)金<=5000),
???????? 備注 text,
???????? constraint CK_日期 check (出生日期<入學(xué)日期)
)
go
create table 課程表
(
???????? 課程號 char(4) not null constraint PK_課程號 primary key ,
--在之后可以單獨定義主鍵就是 constraint 主鍵約束名 primary key(被定義為主鍵的列名)
???????? 課程名稱 char(20) not null,
???????? 上課教師 char(8)
)
go
create table 職工表
(
???????? bmh char(2) not null constraint PK_bmh primary key,
???????? bmmc char(10) not null,
???????? bmszd char(6) not null default'北京'
)
go
/*
?--==創(chuàng)建用戶自定義數(shù)據(jù)類型==--
exec sp_addtype type,system_data_type,'null_type'
exec 執(zhí)行存儲過程
sp_addtype 創(chuàng)建用戶定義數(shù)據(jù)的語句,詳細使用,可以參見SQL聯(lián)機幫助文檔
type 用戶定義的數(shù)據(jù)類型名
system_data_type 系統(tǒng)的數(shù)據(jù)類型(除了int text datetime real類型外,其余類型如numeric float char varchar必須加上單引號,就如上面的例子一樣,否則會出現(xiàn)錯誤)
null_type 是否允許為空
*/
exec sp_addtype 學(xué)生成績,'numeric(5,2)','null'?
--需要使用用戶自定義數(shù)據(jù)類型-學(xué)生成績,故在這里定義一個
create table 成績表
(
???????? 學(xué)號 char(4) not null,
???????? 課程號 char(4) not null,
???????? 平時成績 學(xué)生成績,
???????? 考試成績 學(xué)生成績,
???????? 總成績 學(xué)生成績,
???????? 開學(xué)日期 datetime,
???????? 結(jié)束日期 datetime,
???????? constraint PK_成績表 primary key(學(xué)號,課程號),
???????? constraint FK_學(xué)號 foreign key(學(xué)號) references 學(xué)生基本信息表(學(xué)號),
???????? constraint FK_課程號 foreign key(課程號) references 課程表(課程號)
--創(chuàng)建外鍵約束語法:constratint 外鍵約束名 foreign key(本表中作為外鍵的列名) references 參照表(參照列)
)
轉(zhuǎn)載于:https://www.cnblogs.com/zhanghua518/archive/2008/12/04/1347431.html
總結(jié)
以上是生活随笔為你收集整理的SQL Server-创建表格、各种约束条件的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Smarty 中的 if 语句条件修饰词
- 下一篇: SQLServer-sysobjects