Ensuring All Non-NULL Values Are Unique

Say you have a column in a SQL Server table that allows NULL values. You want this column to be unique when it has a value other than NULL. What’s the best way to program this behavior?

SQL Server has no built-in mechanism to prohibit duplicates exceptNULLs, so you need to implement a custom CHECK constraint to enforce this restriction. For example, the following code snippet enforces exactly this kind the kind of integrity:

 USE tempdbCREATE table t1 (c1 int NULL, c2 char(5) NULL)CREATE trigger mytrigger on t1 for insert, update asBEGIN       IF (select max(cnt) from (select count(i.c1)as cnt from t1, inserted i where t1.c1=i.c1 groupby i.c1) x) > 1       ROLLBACK TRANEND
Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

iOS app development

The Future of iOS App Development: Trends to Watch

When it launched in 2008, the Apple App Store only had 500 apps available. By the first quarter of 2022, the store had about 2.18 million iOS-exclusive apps. Average monthly app releases for the platform reached 34,000 in the first half of 2022, indicating rapid growth in iOS app development.

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a