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
File extentions
Word unable to print picture
ODBC DSN Connection refresh for multiple tables
Duplicating a record in an MS Access Database
Accidentally removed all users from Server 2008
How to format tag right?
How to make a web directory to be an application in Windows 2008 application server/web server?
Auto-Complete problem
C# ,framework 2.0 , bindingsource filter question
Find & Replace on all views, stored procedures, functions in a given database/server