Nee*_*eel 3 database sql-server constants
在MS SQL服务器中,我可以使用SELECT语句来定义CHECK约束吗?假设在理想情况下我必须使用两个表"Customer Master"和"Indian Customer",两个表都完全不同,并且无论如何都不相互关联.但他们共享同一个数据库
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
.
.
.
Run Code Online (Sandbox Code Playgroud)
在表"印度客户"中,我想设置一个约束,以便在此表中委托数据的用户不应该能够进入"客户主数据"中不存在或其分支位置不是IN的客户.表格也在同一个项目中,但并不直接相关.换句话说,你可以说只有来自"客户大师"的印度客户应该在"印度客户"表中.
select CustomerName from "Customer Master"
where Branchlocation = 'IN'
Run Code Online (Sandbox Code Playgroud)
只应在["Indian Customer"]中允许上述查询的输出.[CustomerName]
您可以添加一些额外的约束和超级密钥,并获得您想要的:
CREATE TABLE CustomerMaster (
CustomerName varchar(100) not null,
LocationCode char(2) not null,
constraint PK_CustomerMaster PRIMARY KEY (CustomerName),
constraint UQ_CustomerMaster_Location UNIQUE (CustomerName,LocationCode), /* <-- Superkey here */
constraint CK_CustomerMaster_Locations CHECK (
LocationCode in ('IN','UK','AU')
)
CREATE TABLE IndianCustomer (
CustomerID int not null,
CustomerName varchar(100) not null,
CustomerDetails varchar(max) not null,
LocationCode as 'IN' persisted,
constraint FK_IndianCustomer_CustomerMaster FOREIGN KEY (CustomerName,LocationCode) references CustomerMaster (CustomerName,LocationCode)
)
Run Code Online (Sandbox Code Playgroud)
通过将LocationCode作为IndianCustomer中的计算列,并使用反对超级键的外键,您可以确保数据匹配.
您可以为CustomerName - > CustomerName定义一个额外的FK约束,这在某些情况下可能很有用.
或者,换句话说 - 有一种高度风格化的方法来构建基于"select"语句的约束 - 这是一个外键.但有时您必须添加其他信息(例如超级密钥,计算列)以满足其他过滤要求.
| 归档时间: |
|
| 查看次数: |
7107 次 |
| 最近记录: |