Sql-Server

帶有 ONLY IF 語句的 SQL 檢查約束

  • September 24, 2019

我有一個帶有檢查約束的表,如果 hasdata 列為真,則該表強制數據列不為空。是否可以修改約束以不允許情況 3 發生。即數據不為空只有當有數據為真?

ID  HaveData   Data  
1      0       Null  
2      1       trg$%%D  
3      0       %^&&FFF

您可以通過在CHECK CONSTRAINT中使用 OR 條件來實現此目的。

設置表:

CREATE TABLE dbo.CheckData ([ID] INT IDENTITY,
   [HaveData] BIT NOT NULL,
   [Data] NVARCHAR(25) NULL,
   CONSTRAINT CK_HaveData_Data CHECK (([HaveData] = 0 AND [Data] IS NULL) OR ([HaveData] = 1 AND [Data] IS NOT NULL))
);

添加數據:

-- This works because Data is NULL and HaveData is 0
INSERT INTO CheckData ([HaveData], [Data])
VALUES (0, NULL)

-- This works because Data is not NULL and HaveData is 1
INSERT INTO CheckData ([HaveData], [Data])
VALUES (1, 'trg$%%D')

-- This fails because Data is not NULL and HaveData is 0
INSERT INTO CheckData ([HaveData], [Data])
VALUES (0, '%^&&FFF')

您可以在這個db<>fiddle中看到這一點。

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