I have seen several times people requesting to place a unique constraint on a column that should allow many NULLs but only allow unique values.
Personally, I have never had to implement such a constraint, and when I see the question posed I assume it is needed because of a underlying design problem.
This only works for SQL 2K (as you will see in a minute) and requires various SET commands to be in place both an DDL and DML time...
The following solution places a UNIQUE constraint on a Computed column and according to BOL has restrict requirements...
The ANSI_NULL connection-level option must be set to ON when the CREATE
TABLE statement is executed. The OBJECTPROPERTY function reports whether the
option is on through the IsAnsiNullsOn property.
The connection on which the index is created, and all connections attempting
INSERT, UPDATE, or DELETE statements that will change values in the index, must
have six SET options set to ON and one option set to OFF. The optimizer ignores
an index on a computed column for any SELECT statement executed by a connection
that does not have these same option settings.
These options must be set to ON:
- ANSI_NULLS
- ANSI_PADDING
- ANSI_WARNINGS
- ARITHABORT
- CONCAT_NULL_YIELDS_NULL
- QUOTED_IDENTIFIER
In addition to these ON settings, the NUMERIC_ROUNDABORT option must
be set to OFF
Assume that the column DC is the target of this dodgy constraint...
--DML
CREATE TABLE DodgyConstraint(DC VARCHAR(50) NULL, HelperColoumn INT identity(1,1) NOT NULL,
ComputedConstraint AS CASE WHEN DC IS NULL THEN CAST(HelperColoumn AS VARCHAR(50)) ELSE DC END, UNIQUE (ComputedConstraint))
--Insert 2 nulls
insert DodgyConstraint (DC) Values (NULL)
insert DodgyConstraint (DC) Values (NULL)
--Insert a couple of "real" value
insert DodgyConstraint (DC) Values ('Dave')
insert DodgyConstraint (DC) Values ('Dingo')
--Violation
insert DodgyConstraint (DC) Values ('Dave')
Select * from DodgyConstraint
One of the first things you would do if this type of constraint is needed is to project away the Identity column and the Computed column in a view and never speak of them again...:-)
Print | posted on Friday, May 21, 2004 10:47 AM