Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sub queries in check constraint

I have table designed in SQL-Server 2008 R2.

I have a column in that table which needs to be checked against another table when data is inserting.

ALTER TABLE Table1         WITH CHECK ADD CONSTRAINT CK_Code         CHECK (MyField in (Select Field From Table2)) 

This cause an error

Sub-queries are not allowed in this context. Only scalar expressions are allowed.

I have looked at this question about Check Constraint - Subqueries are not allowed in this context.

Is there any way of achieving this without using a trigger?

like image 794
Highland Avatar asked Oct 21 '12 18:10

Highland


People also ask

Can we use subquery in check constraint?

Sub-queries are not allowed in this context. Only scalar expressions are allowed.

Can you use subquery inside CTE?

¶ A CTE (common table expression) is a named subquery defined in a WITH clause. You can think of the CTE as a temporary view for use in the statement that defines the CTE. The CTE defines the temporary view's name, an optional list of column names, and a query expression (i.e. a SELECT statement).

How can check constraint in SQL query?

The syntax for enabling a check constraint in SQL Server (Transact-SQL) is: ALTER TABLE table_name WITH CHECK CHECK CONSTRAINT constraint_name; table_name. The name of the table that you wish to enable the check constraint.

Can we use in operator in check constraint?

Check constraints are limited to Boolean operations (e.g., =, >=, <=, or <>), though they may include any SQL2003 predicate, such as IN or LIKE. Check constraints may be appended to one another (when checking a single column) using the AND and OR operators.


1 Answers

Note, what you really want is a foreign key constraint. That said, to get a "query" into a check you can write a function that contains the query and outputs a scalar value, then use that function in the check constraint.

CREATE FUNCTION myFunction (     @field DATATYPE(?) ) RETURNS VARCHAR(5) AS BEGIN     IF EXISTS (SELECT* FROM Table2 WHERE MYFIELD = @field)         return 'True'     return 'False' END 

Something like that. Not tested.

Then you can add it to your check like so

ALTER TABLE Table1     WITH CHECK ADD CONSTRAINT CK_Code     CHECK (myFunction(MYFIELD) = 'True') 
like image 183
Johanna Larsson Avatar answered Oct 17 '22 01:10

Johanna Larsson