Sql-Server

檢查約束引用同一表中的另一列

  • January 18, 2018

我有這張表,但檢查約束給我一個錯誤:

‘MedicamentRegulated’ 列的 CHECK 列約束引用了另一列,即表 ‘Medicaments’。

我已經看到這在 SQL Server 中是允許的,但我不知道為什麼它不起作用:/

CREATE TABLE Medicaments (
MedicamentID INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
Name VARCHAR(50),
DateValidity DATE,
MedicamentRegulated BIT CHECK((MedicamentRegulated = 1 AND DateValidity IS NOT NULL) 
 OR MedicamentRegulated = 0)
)

您使用的語法用於列級約束,因此它只能應用於它所附加的列…嘗試在表級別命名您的約束(這也允許鼓勵您為約束提供有意義的名稱可怕的系統預設值):

CREATE TABLE dbo.Medicaments -- always use schema*
(
 MedicamentID INT IDENTITY(1,1) NOT NULL,
 Name VARCHAR(50),
 DateValidity DATE,
 MedicamentRegulated BIT,
 CONSTRAINT pk_Med PRIMARY KEY (MedicamentID),
 CONSTRAINT ck_Med_reg CHECK
 (
   (MedicamentRegulated = 1 AND DateValidity IS NOT NULL) 
   OR MedicamentRegulated = 0
 )
);

*見這篇文章

引用自:https://dba.stackexchange.com/questions/73828