SQL 對 SQLServer 的一些簡單基礎操作



添加約束

--添加主鍵約束

                       alter table 表名add constraint 約束名 primary key(要設爲主鍵的列名)

--添加唯一約束

                       alter table 表名add constraint 約束名 unique(stuName)

--添加檢查約束:

                       alter table 表名add constraint 約束名 check(條件,如:stuSex='男' or stuSex='女')

--添加默認約束:

                       alter table 表名add constraint 約束名 default(要設置的默認值) for stuSex

--添加外鍵約束:

                       alter table 表名add constraint 約束名 foreign key(本表的列名) references 主鍵表名(列名)


一個簡單的例子  包括創建數據庫  外鍵  約束  check  改類型

create database ytf
use ytf
go
/*建S表*/
create table S(Sno char(10) primary key,Sname char(10),Status int,City char(10))
/*建P表*/
create table P(Pno char(10) primary key,Pname char(10),Color int,Weight int)
/*建J表*/
create table J(Jno char(10) primary key,Jname char(10),City char(10))
/*建J表 外鍵的建立*/
create table JPS(Pno char(10),Jno char(10),Sno char(10),QTY char(10),
primary key(Pno,Jno,Sno),
Foreign Key (Pno) references P(Pno),
Foreign Key (Jno) references J(Jno),
Foreign Key (Sno) references S(Sno))
/*爲SPJ表增加一供應日期列,列名爲SUPDATE,日期型*/ 
alter table JPS add SupDate date
/*爲S、P、J表的SNAME、PNAME、JNAME列定義UNIQUE約束;約束名分別命名爲UQ_SNAME, UQ_PNAME,UQ_JNAME;*/ 
alter table S add constraint UQ_SNAME unique(Sname)
alter table P add constraint UQ_PNAME unique(Pname)
alter table J add constraint UQ_JNAME unique(Jname)
/*實現DATE屬性的Check(檢查)約束: SUPDATE<getdate()*/ 
alter table JPS add constraint cons_date_chk check(SupDate<getdate())
/*刪除P表PNAME列的唯一性約束*/ 
alter table P drop constraint UQ_PNAME
/*將P表中PNAME列的數據類型改爲可變字符串型*/
alter table P alter column Pname varchar(50) 
/*用SQL語言在SPJ表上建立一個唯一性索引。*/
create unique index ytf on JPS (QTY)

發佈了23 篇原創文章 · 獲贊 4 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章