I’m facing a confusing problem. If you create a table like the following, you’ll get an error:
CREATE TABLE t
(
a NVARCHAR(100) SPARSE
NULL UNIQUE
)
Msg 1919, Level 16, State 2, Line 1
Column 'a' in table 't' is of a type that is invalid for use as a key column in an index.
Msg 1750, Level 16, State 0, Line 1
Could not create constraint. See previous errors.
But if you create the table first, then create the unique index like this, everything works.
CREATE TABLE t
(
a NVARCHAR(100) SPARSE
NULL
)
CREATE UNIQUE NONCLUSTERED INDEX t_a ON dbo.t
(
a
)
Anyone can help me to explain it please?
Thank you!
I don’t know why, but from MSDN SPARSE columns
Now, into conjecture land…
It kind of makes sense because a UNIQUE constraint can not be filtered, whereas an explicit index can. Hence the UNIQUE constraint is disallowed but allowed via CREATE INDEX where you have an implied filter.
I’d also say disallowed for clustered indexes because every non-clustered index refers to the clustered index + clustered indexes have to be internally unique if not explicitly (“uniquifier”). So every row must exist.
Taken together, you have to have something for unique and/or clustered: which would defeats the point of using SPARSE… no?