SQL Server allows repeated null fields and does not have null values (1/2)

Source: Internet
Author: User
Solution 1: for this problem, the first thought may be: Can I add a unique key to the caption field? Well, let's proceed with this idea and create a unique index first. & Nbsp; Code: createuniquenonclusteredindexun_test_tbontest_tb (caption) go index has been created. Let's test the effect & nbsp; Code: I solution 1:
For this question, the first thought may be: Can I add a unique key to the caption field? Well, let's proceed with this idea and create a unique index first.
The Code is as follows:
Create unique nonclustered index un_test_tb
On test_tb (caption)
Go

After the index is created, let's test the effect.
The Code is as follows:
Insert into test_tb (caption)
Values (null)
Go
Insert into test_tb (caption)
Values (null)
Go

After running, we will receive the following error message:
Reference content is as follows:
Message 2601, Level 14, status 1, 1st rows
Rows with duplicate keys cannot be inserted in the 'dbo. test_tb 'object with the unique index 'un _ test_tb.
The statement has been terminated.
Therefore, this solution does not work.
Solution 2:
Add constraints so that SQL server can first verify whether the value to be inserted exists in the existing data when inserting data. Because this constraint is not a simple operation, we first create a function and then call it in the constraint.
Create a verification logic function:
The Code is as follows:
Create function [dbo]. [fn_ck_test_tb_caption] ()
Returns bit
As
Begin
If (exists (
Select 1
From test_tb as
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.