Sql Server外键约束

时间:2023-03-09 15:25:51
Sql Server外键约束
一、添加约束(级联删除)
1、创建表结构时添加
create table UserDetails
(
id int identity(1,1) primary key,
name varchar(50) not null, --真实姓名
userId int,
foreign key (userId) references UserInfo(UserId) on delete cascade
)
2、表结构已存在时添加
ALTER TABLE [dbo].[API_User_Label]  WITH CHECK Add CONSTRAINT [FK_API_User_Label_API_SearchLabel] FOREIGN KEY([LabelId])
REFERENCES [dbo].[API_SearchLabel] ([Id]) on delete cascade
GO
二、删除约束
ALTER TABLE [dbo].[API_User_Label] 
drop constraint FK_API_User_Label_API_SearchLabel
Go