I can't think of a way to do this with a table constraint. You can only have a single row with a NULL if you put a unique constraint on a column.You can do it with a unique index on a View where the view does not include the rows containing the NULLs.create table dbo.MyTable (ID int not null identity(1,1) primary key clustered,ColA varchar (20) null)goCreate view dbo.MyViewwith SCHEMABINDINGasSelect ID , ColA from dbo.MyTablewhere ColA is not nullgocreate unique clustered index MyIndex on dbo.MyView ( ColA )go-- OKinsert into dbo.MyTable (ColA) select 'a'go-- Will fail on dupe keyinsert into dbo.MyTable (ColA) select 'a'go-- OKinsert into dbo.MyTable (ColA) select nullgo--OKinsert into dbo.MyTable (ColA) select nullgoselect * from dbo.MyTablegodrop view dbo.MyViewgodrop table dbo.MyTable
Results:ID ColA ----------- -------------------- 1 a3 NULL4 NULL(3 row(s) affected)
There are other issues with indexed views that I won't get into now, so make sure you really need this.You might also be able to do it with a trigger.CODO ERGO SUM