[英]How do I add a constraint to check if value is present in another column within the same table?
I have an entity like this,我有一个这样的实体,
@Entity
@Table(name = "Persons", schema="PU")
public class Persons {
@Basic
@Column(name = "PERSON_ID")
private String personId
@Basic
@Column(name = "PERSON_NAME")
private String personName
@Basic
@Column(name = "PERSON_NAME_COPY")
private String personNameCopy
}
I want to add a constraint in the personNameCopy column such that whatever value is being inserted in that column should be present in the personName column.我想在 personNameCopy 列中添加一个约束,以便在该列中插入的任何值都应该出现在 personName 列中。
Is there any way to achieve this?有什么办法可以做到这一点?
DROP TABLE IF EXISTS dbo.Person;
CREATE TABLE dbo.Person
(
PERSON_ID INT NOT NULL PRIMARY KEY,
PERSON_NAME VARCHAR(50)NOT NULL,
PERSON_NAME_COPY VARCHAR(50)NOT NULL,
CONSTRAINT CHK_PERSON_NAME_PERSON_NAME_COPY CHECK (PERSON_NAME=PERSON_NAME_COPY)
)
GO
INSERT dbo.Person(PERSON_ID,PERSON_NAME,PERSON_NAME_COPY)
VALUES(1,'KUMAR','KUMAR')
--THIS ROW IS TO BE REJECTED
INSERT dbo.Person(PERSON_ID,PERSON_NAME,PERSON_NAME_COPY)
VALUES(2,'JOHN','KUMAR')
SELECT *FROM DBO.Person;
if I understand your question correctly you can implement check constraint (example is above) Please also have look https://learn.microsoft.com/en-us/sql/relational-databases/tables/create-check-constraints?view=sql-server-ver16如果我正确理解你的问题,你可以实施检查约束(上面的例子)请也看看https://learn.microsoft.com/en-us/sql/relational-databases/tables/create-check-constraints?view= sql-server-ver16
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.