Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CHECK CONSTRAINT on multiple columns

I use SQL Server 2008

I use a CHECK CONSTRAINT on multiple columns in the same table to try to validate data input.

I receive an error:

Column CHECK constraint for column 'AAAA' references another column, table 'XXXX'.

CHECK CONSTRAINT does not work in this way.

Any other way to implement this on a single table without using FK?

Thanks

Here an example of my code

CREATE TABLE dbo.Test  (    EffectiveStartDate  dateTime2(2)        NOT NULL, EffectiveEndDate    dateTime2(2)        NOT NULL     CONSTRAINT CK_CmsSponsoredContents_EffectiveEndDate CHECK (EffectiveEndDate > EffectiveStartDate), ); 
like image 868
GibboK Avatar asked Aug 09 '10 07:08

GibboK


People also ask

How do I create a check constraint on multiple columns in SQL Server?

SQL check constraint referring to multiple columns To create this data validation rule, we will use the CHECK(LastCensus<NextCensus)) expression in the table creation query. Now we want to add a row to the CountryListCensus table, but with equal values ​​of column LastCensus and column LastCensus.

Can you have multiple check constraints in a table?

You can apply multiple CHECK constraints to a single column. You can also apply a single CHECK constraint to multiple columns by creating it at the table level.

What is multi column constraint?

When you use the multiple-column constraint format to define check constraints, a check constraint can apply to more than one column in the same table. (You cannot, however, create a check constraint whose condition uses a value from a column in another table.)


2 Answers

Yes, define the CHECK CONSTRAINT at the table level

CREATE TABLE foo (    bar int NOT NULL,     fred varchar(50) NOT NULL,     CONSTRAINT CK_foo_stuff CHECK (bar = 1 AND fred ='fish') ) 

You are declaring it inline as a column constraint

... fred varchar(50) NOT NULL CONSTRAINT CK_foo_fred CHECK (...) ... 

Edit, easier to post than describe. Fixed your commas.

CREATE TABLE dbo.Test  (      EffectiveStartDate  dateTime2(2)        NOT NULL,   EffectiveEndDate    dateTime2(2)        NOT NULL,  --need comma   CONSTRAINT CK_CmsSponsoredContents_EffectiveEndDate CHECK (EffectiveEndDate > EffectiveStartDate) --no comma ); 

Of course, the question remains are you using a CHECK constraint where it should be an FK constraint...?

like image 192
gbn Avatar answered Oct 15 '22 23:10

gbn


Check constraints can refer to a single column or to the whole record.

Use this syntax for record-level constraints:

ALTER TABLE MyTable ADD CONSTRAINT MyCheck CHECK (...your check expression...) 
like image 36
devio Avatar answered Oct 15 '22 21:10

devio