In MS SQL server, can i use a SELECT statement to define a CHECK constraint? Say i have to work with two tables “Customer Master” and “Indian Customer” in ideal situation both tables are compleatly different, and are not interrelated in anyways. however they share the same database
Content of "Customer Master":
CustomerName (colomn): a, b, c, d, e
Branchlocation (colomn): IN, AU, IN, IN, UK
Content of "Indian Customer":
customerID (colomn): 1, 2, 3
CustomerName (colomn): a, c, d
customer details (colomn): details1, details, details
.
.
.
In Table “Indian Customer” i want to put a constraint so that the users entring data in this table should not be able to enter customers that dont exist in “Customer Master” or whose branch location is not IN. also the tables are in the same project but are NOT directly related . In other words you can say Only indian customer from “Customer Master” should be in table “Indian Customer”.
select CustomerName from "Customer Master"
where Branchlocation = 'IN'
the output of the above query should only be allowed in [“Indian Customer”].[CustomerName]
You can add some additional constraints and superkeys, and get what you want:
By having LocationCode as a computed column in IndianCustomer, and having the foreign key against the superkey, you’re ensuring the data matches.
You can define an additional FK constraint just for CustomerName -> CustomerName, this can prove useful in some circumstances.
Or, to put it another way – there is one, highly stylised way to construct a constraint based on a “select” statement – and that is a FOREIGN KEY. But you sometimes have to add additional information (such as super keys, computed columns) to satisfy additional filtering requirements.