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

bjg7j2ky  于 2023-02-02  发布在  Java
关注(0)|答案(1)|浏览(125)

我有一个这样的实体,

@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
}

我想在personNameCopy列中添加一个约束,以便插入该列的任何值都应该出现在personName列中。
有没有办法做到这一点?

lf5gs5x2

lf5gs5x21#

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;

如果我正确理解了您问题,您可以实现检查约束(示例如上所示)请同时查看https://learn.microsoft.com/en-us/sql/relational-databases/tables/create-check-constraints?view=sql-server-ver16

相关问题