索引創建好了,我們來測試下效果
代碼如下:
insert into test_tb (caption)
values (null)
go
insert into test_tb (caption)
values (null)
go
運行之后我們會收到下面的錯誤信息:
以下為引用的內容:
消息 2601,級別 14,狀態 1,第 1 行
不能在具有唯一索引 'un_test_tb' 的對象 'dbo.test_tb' 中插入重復鍵的行。
語句已終止。
所以該解決方案是不行的。
解決方案2:
添加約束,讓sql server在插入數據的時候,先驗證下已有數據中是否有現在要插入的這個值。由于這個約束不是簡單的一個運算,因此我們先創建一個函數,然后再在約束中調用這個函數。
創建驗證邏輯函數:
代碼如下:
create function [dbo].[fn_ck_test_tb_caption]()
returns bit
as
begin
if(exists(
select 1
from test_tb as a
where (caption is not null) and exists
(select 1 as expr1
from test_tb
where (caption is not null) and (caption = a.caption) and (a.testid <> testid))
))
return 0
return 1
end
go
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com