Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a Check constraint relate to another table?

Let's say I have one table called ProjectTimeSpan (which I haven't, just as an example!) containing the columns StartDate and EndDate.

And that I have another table called SubProjectTimeSpan, also containing columns called StartDate and EndDate, where I would like to set a Check constraint that makes it impossible to set StartDate and EndDate to values "outside" the ProjectTimeSpan.StartDate to ProjectTimeSpan.EndDate

Kind of a Check constraint that knows about another tables values...

Is this possible?

like image 624
Jack Johnstone Avatar asked Oct 07 '10 10:10

Jack Johnstone


People also ask

Can a check constraint references another table?

1. Check constraint cannot allow to refer the columns from other tables.

Which constraint is used to relate two tables?

A Foreign Key is a database key that is used to link two tables together. The FOREIGN KEY constraint identifies the relationships between the database tables by referencing a column, or set of columns, in the Child table that contains the foreign key, to the PRIMARY KEY column or set of columns, in the Parent table.

What are the limitations of check constraint?

The condition must be a Boolean expression evaluated using the values in the row being inserted or updated and can't contain sub queries, sequence, the SYSDATE,UID,USER or USERENV SQL functions, or the pseudo columns LEVEL or ROWNUM.

Can a same constraint be used in 2 tables?

You can add the same constraint, but not with the same name.


1 Answers

In response to your comment on GSerg's answer, here's an example check constraint using a function:

alter table YourTable add constraint chk_CheckFunction check (dbo.CheckFunction() = 1) 

Where you can define the function like:

create function dbo.CheckFunction() returns int as begin     return (select 1) end 

The function is allowed to reference other tables.

like image 177
Andomar Avatar answered Sep 30 '22 01:09

Andomar