2

Hi all and thanks for your advice.

Expense(SupplierID(Foreign Key), DocumentID(vchar))

I understand how to add a simple unique constraint on two columns. However, if DocumentID = 'NA', I would like to ignore the rules of the constraint.

Some suppliers in our system do not provide an invoice id, for example. Therefore, I leave the field NULL. I would like to remove all nulls for the field 'DocumentID' to avoid accounting for the NULLS in my client code.

I am new to SQL Server, but I could figure out how to do this using a trigger. The reason I'm asking here is to see if there is a better way to respond to this scenario or to avoid it by a different design.

Thanks!

Thanks Tibor. I was unable to enter a comment correctly, I suppose. This is what I ended up with using your method.

use CMRBE 
CREATE UNIQUE NONCLUSTERED INDEX idx_SupplierID_DocumentID 
ON Expense(SupplierID, DocumentID) 
WHERE DocumentID <> 'NA';
asked Aug 8, 2020 at 13:20
4
  • I highly recommend <> over != - sqlblog.org/2008/03/20/which-to-use-or Commented Aug 9, 2020 at 0:54
  • @Aaron Thank you Aaron. I read the article. Thanks!. Will be using <> as I am comfortable with either. Commented Aug 9, 2020 at 16:38
  • 1
    A bit of time travel there, referring to Aaron's blog post. :-) Still valid, though. Tom, did the index solve your problem? Commented Aug 10, 2020 at 8:44
  • 1
    Please, please re-post your solution as an answer and remove it from the question, thank you. Commented Aug 10, 2020 at 8:55

2 Answers 2

3

You can create a unique index with a where clause to filter out those values for which you want to avoid duplicates.

answered Aug 8, 2020 at 15:05
0
1

Thanks Tibor. This is what I ended up with and it fits the bill.

use CMRBE 
CREATE UNIQUE NONCLUSTERED INDEX idx_SupplierID_DocumentID 
ON Expense(SupplierID, DocumentID) 
WHERE DocumentID <> 'NA';
answered Aug 11, 2020 at 9:25

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.