1. 程式人生 > >SQL資料庫建表、表中列的常見型別與一些常用約束的操作

SQL資料庫建表、表中列的常見型別與一些常用約束的操作

硬是一拖再拖,直到了今天才更。敲打

--表中列的型別

 -- int  整型
 -- char(10)字串  固定長度查詢速度快,浪費空間如身份證號 手機號碼 學號
 --varchar(10) 字串可變長度姓名       地址
 -- 不帶n的:字元或者數字佔一個位元組,漢字為兩個位元組
 -- 帶n的:雙位元組儲存,字母或者數字、漢字兩個位元組
 -- nchar(10)
 -- nvarchar(10)
 -- 存圖片時,圖片上傳到伺服器上,在資料庫只存路徑




 -- 建表語句
 use studentmanager
 if exists(select *from sysobjects where name='table_student')
drop table table_student
 create table table_student
 (
--欄位名 欄位的特徵
id int identity(1,1) primary key,--在建立表時就設定為主鍵列與自增列
stu_number char(12) not null,--不允許為空
stu_name varchar(20) not null,
stu_age int,
birthday datetime,
class_id int references table_class(class_id) --外來鍵
 )
 create table table_class
 (
class_id int identity(1,1) primary key,
class_name varchar(20) not null,
create_time datetime
 )


 -- 約束的目的 確保表中資料的完整性
 --行完整性(實體完整性):主鍵約束與唯一約束
 -- 列完整性(域完整性)  :檢查約束、預設約束與非空約束
 -- 參照完整性 :外來鍵約束
 use studentmanager
 drop table table_class
 drop table table_student
 if exists(select *from sysobjects where name='table_student')
drop table table_student
 create table table_student
 (
--欄位名 欄位的特徵
id int not null,
stu_number char(12),
stu_name varchar(20) ,
stu_age int,
birthday datetime,
class_id int
 )
 create table table_class
 (
class_id int not null,
class_name varchar(20),
create_time datetime
 )
 -- 追加約束
-- 主鍵約束(向哪個表 加什麼約束 加在哪個列上面) 非空唯一
alter table table_student
add constraint PK_id primary key(id)
alter table table_class
add constraint PK_class_id primary key(class_id)
--唯一約束  可以為空 但唯一 只允許一個為空
alter table table_student
add constraint UK_stu_number unique(stu_number)
--檢查約束
alter table table_student
add constraint CK_stu_age check(stu_age>0 and stu_age<150)
--預設約束
alter table table_class
add constraint DF_create_time default(getdate()) for create_time
--外來鍵約束
alter table table_student 
add constraint FK_class_id foreign key (class_id) references table_class(class_id)


--建表時直接加約束
 --create table table_student
--(
--id int identity(1,1) primary key,
--stu_number char(12) unique not null,
--stu_name varchar(20) not null,
--stu_age int check(stu_age>0 and stu_age<150),
--birthday datetime default(getdate()),
--class_id int references table_class(class_id)
-- )


--刪除約束
alter table table_student

drop constraint UK_stu_number

--------攜著一股什麼也不服的勁在活著