Sql Server 自定義約束 實現:某列 可空,但非空值唯一不重復
標簽:
SQL Server
案例:
1、准备表
create table student( --学生表
id int primary key identity(1,1), --自增主键
name nvarchar(255), --姓名
student_no varchar(255) --学号
)
<br><br>
2、 应用场景
一个学生表,学号不能重复,但是插入数据是又不能立刻决定,而需要后期更新,所以一开始学号是空值,后期更新,所以就产生了标题中的需求。列可以为空,但是如果有值的话,值不能重复。
<br><br>
3、自定义约束函数
create function student_no_unique(@arg varchar(255))
returns bit
as
begin
declare @result bit
if((select COUNT(*) from student stu where stu.student_no is not null and stu.student_no=@arg)>1)
set @result = 0
else
set @result = 1
return @result
end
解释几个地方:
1.@arg 是函数的参数,数据类型要和该列一致。
2.if条件使用 >1,而不是 >0,如果是大于0的话,只能插入空值。我猜想约束的执行过程是:插入数据 > 验证数据是否符合约束 > 若不符合,则回滚。
<br><br>
4、增添约束
alter table student
add constraint student_no_unique_constraint check (dbo.student_no_unique(student_no)=1)
将要插入的数据的student_no作为参数传递给函数。
<br><br>
5、测试数据
insert into student values('name1',null)
insert into student values('name2',null)
insert into student values('name3','123456')
insert into student values('name4','123456')
insert into student values('name5','123')
执行结果为
(1 行受影响)
(1 行受影响)
(1 行受影响)
消息 547,级别 16,状态 0,第 4 行
INSERT 语句与 CHECK 约束"student_no_unique_constraint"冲突。该冲突发生于数据库"OnlineStore",表"dbo.student", column 'student_no'。
语句已终止。
(1 行受影响)
點擊查看更多內容
1人點贊
評論
評論
共同學習,寫下你的評論
評論加載中...
作者其他優質文章
正在加載中
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦