2

I have two tables, one with columns accountid, category, code, name, desc and the other with columns id, accountid, code, reason, desc, active.

Is there any way I can create a constraint such that code in the second table contains only values of code that are in first table with condition where category is somevalue?

8
  • depends on your database engine Commented Aug 4, 2017 at 0:35
  • What does that mean? (i am novice to sql server(ssms)) Commented Aug 4, 2017 at 0:38
  • please tag the database you are using. ty Commented Aug 4, 2017 at 0:39
  • @FerdinandGaspar do you mean schema for tables Commented Aug 4, 2017 at 0:45
  • 1
    What FerdinandGaspar meant was for you to add the blue-boxed sql-server to the list of other blue-boxes at the bottom of your question. Like what I've just done for you ;) Commented Aug 4, 2017 at 1:50

2 Answers 2

2

One method is a little trick. First, create a unique index on (category, code) in the first table:

create unique index unq_table1_category_code on table1(category, code)

Then create a computed column in table2:

alter table table2 add category as ('somevalue') persisted;

Then create the foreign key relationship:

alter table table2 add constraint fk_somevalue_code
    foreign key (category, code) references table1(category, code);
Sign up to request clarification or add additional context in comments.

2 Comments

I don't think it will work if the category + code isn't unique in the referenced table. Although, one can always throw the parent table' PK in, just to guarantee uniqueness (assuming it exists, of course).
@RogerWolf . . . If the values are not unique, then a foreign key could not be used.
0
ALTER TABLE table2 WITH CHECK
  ADD CONSTRAINT CK_table2category CHECK (category = 'somevalue'),
      CONSTRAINT FK_table2code FOREIGN KEY (code) REFERENCES table1 (code);

2 Comments

This is not working,sql server throwing error near where clause
ALTER TABLE [dbo].[StatusReason] WITH NOCHECK ADD CONSTRAINT [CK_StatusReason_ValueItem] CHECK([Category]='Status'), CONSTRAINT [FK_StatusReason_ValueItem] FOREIGN KEY([StatusCode]) REFERENCES [dbo].[ValueItem] ([Code]) GO ALTER TABLE [dbo].[StatusReason] CHECK CONSTRAINT [CK_StatusReason_ValueItem], [FK_StatusReason_ValueItem] GO

Your Answer

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.