CREATE TABLE dbo.Foo (
keycol INT NULL,
datacol CHAR(1));
GO
CREATE VIEW UniqueFoo WITH SCHEMABINDING
AS
SELECT keycol, datacol
FROM dbo.Foo
WHERE keycol IS NOT NULL;
GO
CREATE UNIQUE CLUSTERED INDEX ix_UniqueFoo
ON UniqueFoo(keycol);
GO
-- OK, multiple NULL values allowed
INSERT INTO dbo.Foo VALUES(1, 'a');
INSERT INTO dbo.Foo VALUES(NULL, 'b');
INSERT INTO dbo.Foo VALUES(NULL, 'c');
GO
-- Error, attempt to insert duplicate keycol value
INSERT INTO dbo.Foo VALUES(1, 'd');
/*
Msg 2601, Level 14, State 1, Line 2
Cannot insert duplicate key row in object 'dbo.UniqueFoo' with unique index 'ix_UniqueFoo'.
The statement has been terminated.
*/
CREATE UNIQUE NONCLUSTERED INDEX ix_Foo
ON Foo (keycol)
WHERE keycol IS NOT NULL;
Labels: t-sql programming