SQL Server允許重複空欄位不空值解決方案(1/2)

來源:互聯網
上載者:User

解決方案1:
對於這個問題,大家的第一個想法可能是:在caption這個欄位上面加一個唯一鍵不就可以了嗎?好,我們按著這個思路做下去,先建立唯一索引。
 代碼如下:
create unique nonclustered index un_test_tb
on test_tb(caption)
go

索引建立好了,我們來測試下效果
 代碼如下:
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

首頁 1 2 末頁

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.