I need a relationship between a contract (CompanyId) and a company (CompanyId) with a company type is equal to 1.
ALTER TABLE [dbo].[Contract] WITH CHECK ADD CONSTRAINT [FK_Contract_Company] FOREIGN KEY([CompanyId])
REFERENCES [dbo].[Company] ([CompanyId]) WHERE CompanyTypeId = 1
You can't have a where clause on a foreign key constraint.
However, you can use a regular foreign key constraint and also a check constraint, where your check expression will be if the
CompanyTypeId
is actually 1 for theCompanyId
that you try to insert intocontract
.To do that you will need to create a user defined function that will do the actual test and return a value. for example:
And then in your check constraint you should execute this function and check if the returned value is higher then 0 (should probably be 0 or 1 in your case):