SQL Server 數據庫添加主鍵,唯一鍵,外鍵約束腳本


 

-- 聲明使用數據庫
use 數據庫;
go

-- 添加主鍵(primary key)約束
-- 基本語法
-- 判斷主鍵約束是否存在,如果存在則刪除,不存在則添加
if exists(select * from sysobjects where name=主鍵名)
alter table 表明 drop constraint 主鍵名;
go

alter table 表明 add constraint 主鍵名 primary key(列名)

use SapDBT;
go
-- 實際例子 
if exists(select * from sysobjects where name='PK_student_id')
alter table [dbo].[Student] drop constraint PK_student_id;
go

alter table [dbo].[Student] add constraint PK_student_id primary key([ID])

 

-- 添加唯一鍵(UNIQUE)約束
-- 基本語法
-- 判斷唯一鍵約束是否存在,如果存在則刪除,不存在則添加
if exists(select * from sysobjects where name=約束名)
alter table 表明 drop constraint 約束名;
go

alter table 表明 add constraint 約束名 primary key(列名)

-- 實際例子 
if exists(select * from sysobjects where name='UQ_student_name')
alter table [dbo].[Student] drop constraint UQ_student_name;
go

alter table [dbo].[Student] add constraint UQ_student_name unique([Name])

 

-- 添加外鍵(foreign key)約束
-- 基本語法
-- 判斷外鍵約束是否存在,如果存在則刪除,不存在則添加
if exists(select * from sysobjects where name=約束名)
alter table 表明 drop constraint 約束名;
go

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

-- 實際例子
if exists(select * from sysobjects where name='FK_Score_Student')
alter table [dbo].[Score] drop constraint FK_Score_Student;
go

-- [dbo].[Score]中的外鍵[StudentId]是[dbo].[Student]的主鍵
alter table [dbo].[Score] add constraint FK_Score_Student foreign key([StudentId]) references [dbo].[Student]

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM