Last active
January 2, 2022 15:06
-
-
Save shahabganji/6cd86e2b079284cd4f787e46001709f8 to your computer and use it in GitHub Desktop.
Ensure Uniqueness of Nullable Columns
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ALTER TABLE dbo.Employee | |
DROP Constraint UQ_Employee_SSN | |
GO | |
ALTER TABLE dbo.Employee | |
ADD SSN_CMPTD AS | |
CASE | |
WHEN SSN IS NOT NULL | |
THEN SSN | |
ELSE | |
CAST( Id AS Char(10) ) | |
END | |
GO | |
ALTER TABLE dbo.Employee | |
ADD CONSTRAINT UQ_Employee_SSN_CMPTD UNIQUE(SSN_CMPTD) | |
GO |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE TABLE dbo.Employee( | |
Id BIGINT NOT NULL IDENTITY | |
CONSTRAINT PK_Employee_Id Primary KEY | |
, FirstName nVarChar(50) NOT NULL | |
, LastName nVarChar(100) NOT NULL | |
, SSN Char(10) NULL | |
CONSTRAINT UQ_Employee_SSN UNIQUE | |
) | |
ON [PRIMARY] | |
GO |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Msg 2627, Level 14, State 1, Line 1 | |
Violation of UNIQUE KEY constraint 'UQ_Employee_SSN'. Cannot insert duplicate key in object 'dbo.Employee'. The duplicate key value is (<NULL>). |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ALTER TABLE dbo.Employee | |
DROP CONSTRAINT UQ_Employee_SSN_CMPTD | |
GO | |
ALTER TABLE dbo.Employee | |
DROP COLUMN SSN_CMPTD | |
GO | |
CREATE UNIQUE NONCLUSTERED INDEX Idx_Employee_SSN | |
ON dbo.Employee( SSN ) | |
WHERE SSN IS NOT NULL | |
GO |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
INSERT INTO dbo.Employee( FirstName , LastName , SSN ) | |
VALUES( 'Jane' , 'Doe' , NULL ) | |
INSERT INTO dbo.Employee( FirstName , LastName , SSN ) | |
VALUES( 'John' , 'Doe' , NULL ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment