SQL Server allows you to resolve the null value of a duplicate null field (1/2)

Source: Internet
Author: User

Solution 1:
The first idea for this question may be: Is it OK to add a unique key to the caption field? OK, let's follow this thread and create a unique index first.
The code is as follows:
Create unique nonclustered index UN_TEST_TB
On TEST_TB (caption)
Go

Index creation Okay, 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 receive the following error message:
The following are the referenced contents:
Message 2601, Level 14, State 1, line 1th
You cannot insert a row of duplicate keys in an object ' DBO.TEST_TB ' with a unique index ' UN_TEST_TB '.
The statement was terminated.
So the solution is not going to work.
Solution 2:
Add a constraint so that SQL Server, when inserting data, verifies that there is a value in the existing data that is now being inserted. Since this constraint is not a simple operation, we first create a function and then call the function in the constraint.
To create a validation 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 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

Home 1 2 last page
Related Article

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.