简体   繁体   English

如何添加约束以检查同一个表中的另一列中是否存在值?

[英]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.

相关问题 检查现有表以插入一列,该值是否存在? - check the existing table to insert a column, the value is present there or not? 如何检查输入(整数)是否与数组中存在的另一个值(整数)匹配? - How do I check if a input (integer) matches another value (integer) that exits within my array? 当同一 class 中的另一个属性的值更新时,如何动态更新 java 属性 - How do I dynamically update a java property when the value of another property within the same class is updated 如何检查类名中是否存在单词? - How do I check if a word is present in the classname? 如何检查 java 中的 cassandra 表中是否存在列? - how do I check if a column exists in cassandra table in java? 如何计算数组中相同值的多个实例? - How do I count multiple instances of the same value within an array? 如何检查圆形数组的连续位置中是否存在相同的值? - How to check if same value is present in consecutive locations in a circular array? 如何检查数组是否与参数具有相同的值? - how do I check if an array has the same value as the parameter? 如何在 android 工作室的同一或其他表的另一个微调器中添加另一列 - how to add another column in another spinner of same or other table in android studio 如何添加到 mysql 列中的现有值? - How do I add onto an existing value in a column of mysql?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM