Solved

Need a UNIQUE constrain on multiple cols in a SQL Server table but one of the cols is by VALUE

Posted on 2014-07-30
4
333 Views
Last Modified: 2014-08-04
Say I have this simple example table

username varchar(100),
active char(1),
date_deactivated datetime

I need to have a UNIQUE constraint on this table where there can only be one username that has active="y". There can be any number of the same username and "n" rows. Appreciate the help in advance.
0
Comment
Question by:CodeWrangler
  • 2
  • 2
4 Comments
 
LVL 69

Accepted Solution

by:
ScottPletcher earned 500 total points
ID: 40230097
You can't do it directly, but it's fairly easy to "kludge" this.

1) Make sure the table has a unique value, such as an identity column; add an identity if you need to;
2) Add a persisted, computed column to use in the index.

ALTER TABLE dbo.tablename
ADD active_index AS CASE WHEN active = 'Y' THEN 0 ELSE ident END PERSISTED

CREATE UNIQUE {CLUSTERED|NONCLUSTERED} INDEX index_name ON dbo.tablename ( username, active_index ) WITH ( FILLFACTOR = ..., SORT_IN_TEMPDB = ON ) ON [your_filegroup_name]
0
 

Author Comment

by:CodeWrangler
ID: 40239513
Thanks a ton!!
0
 

Author Comment

by:CodeWrangler
ID: 40239518
just curious, how much will this affect performance. I know you only have limited information about my table and it's design, but strictly from this approach of having a index use a computer column, which might be the performance impact.
0
 
LVL 69

Expert Comment

by:ScottPletcher
ID: 40239570
Virtually zilch.  There's some slight overhead to generating an identity column, but most people use one in a table anyway.
0

Featured Post

Zoho SalesIQ

Hassle-free live chat software re-imagined for business growth. 2 users, always free.

Join & Write a Comment

Suggested Solutions

If you have heard of RFC822 date formats, they can be quite a challenge in SQL Server. RFC822 is an Internet standard format for email message headers, including all dates within those headers. The RFC822 protocols are available in detail at:   ht…
Ever wondered why sometimes your SQL Server is slow or unresponsive with connections spiking up but by the time you go in, all is well? The following article will show you how to install and configure a SQL job that will send you email alerts includ…
This video shows how to set up a shell script to accept a positional parameter when called, pass that to a SQL script, accept the output from the statement back and then manipulate it in the Shell.
Via a live example, show how to extract insert data into a SQL Server database table using the Import/Export option and Bulk Insert.

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now