Microsoft
Software
Hardware
Network
Question : Unique index that ignores null values
I have a table in which there is a field called UserName. This field is not the primary key but it needs to be a unique key. This value is often left as null.
I built a unique index on that field but I had to remove it because null values are seen as duplicates. Is there a way to enforce uniqueness only if the value is not null.
Answer : Unique index that ignores null values
You must create a unique constraint if you need to enforce uniqueness of column UserName. However, This can be done if there are any duplicate values. Because of UserName column is nullable, you have a lot of null values previously stored in it.
To resolve your problem, do the following:
1] Replace all null values with a unique value (I suggest GUID).
2] Create a UNIQUE constraint on column UserName.
3] Create a trigger to replace Null value on UserName column with GUID.
Check next code and let me know if works for you.
-- 1] Replace all null values with a
-- unique value.
declare cr_User cursor local
for select UserName
from Users
where Username
is null
open cr_User
while 1=1
begin
fetch cr_User
if @@fetch_status<>0 break
update Users
set UserName
=cast(newid() as varchar(36))
where current of cr_User
end
-- 2] Create a UNIQUE constraint on
-- column UserName
alter table users add constraint UQN_UserName unique (UserName)
-- 3] Create a trigger to replace Null
-- value on UserName column with
-- GUID.
create trigger TG_Users on Users
for insert,update
as
begin
update Users
set UserName
=cast(newid() as varchar(36))
from Inserted
where Users.UserId
=Inserted.UserId
end
PD: You don’t mention anything about your table’s structure so I assume UserName is varchar datatype column with at least 36-character length.
Random Solutions
Terminal Server into 2 seperate servers
Microsoft, Server 2003, SP2 Bugcheck 0x0000000a Problem
Help with multiselect listbox
MS Excel, MS Office
MS Access calculate rolling 12 month average
Access multile servers by RDP thru ISA 2006
Delete subjob record when delete main table record
adding a windows 2008 server
Can I install MS EBS 2008 without Security server?
How to override some Machine.config info