![](/img/trans.png)
[英]Issue with multi-column In predicates are not supported in the DELETE condition
[英]Multi-Column check constraint
考慮一個簡單的表..
create table dbo.car( car_guid UNIQUEIDENTIFIER default(newid())
, car_type varchar(20) not null
, wind_protector varchar(20) not null
)
insert into dbo.car(car_type, wind_protector) VALUES('HARD_TOP', 'NA')
insert into dbo.car(car_type, wind_protector) VALUES('CONVERTIBLE', 'FLAPBLAST_3')
insert into dbo.car(car_type, wind_protector) values('CONVERTIBLE', 'FLAPBLAST_2')
我正在嘗試制作一個檢查約束,說明如果 car_type 是“CONVERTIBLE”,則 wind_protector 可以是“FLAPBLAST_2”或“FLAPBLAST_3”。 否則 wind_protector 的值為“NA”。 該列不能是 null。
我寫了基本的檢查約束..
([wind_protector]='FLAPBLAST_3' OR [wind_protector]='FLAPBLAST_3')
我一直堅持跨兩列編寫檢查約束並使用和或邏輯。
有可能做我想要完成的事情嗎?
謝謝,
我認為您受到以下約束:
alter table car
add constraint chk1
check (
( car_type='CONVERTIBLE' and wind_protector in ('FLAPBLAST_2','FLAPBLAST_3'))
or wind_protector='NA'
);
您可以使用帶有AND
OR
邏輯的簡單多列約束來執行此操作
CHECK (
car_type = 'CONVERTIBLE' AND wind_protector IN ('FLAPBLAST_2', 'FLAPBLAST_3')
OR
car_type = 'CONVERTIBLE' AND wind_protector = 'NA'
)
但是您不想在這里使用check
約束。 wind_protector
不是Car
的屬性,它是CarType
的屬性。 它可以有多個wind_protector
。
因此,您需要將您的架構規范化為適當的第三范式。 您還需要幾個表: CarType
包含每種汽車類型。 然后WindProtector
表包含防風器的可能選項。 最后是一個連接它們並定義哪些組合是可能的表:
create table dbo.CarType (
car_type varchar(20) not null primary key
);
insert dbo.CarType (car_type) VALUES
('HARD_TOP'),
('CONVERTIBLE');
create table dbo.WindProtector (
wind_protector varchar(20) not null primary key
);
insert dbo.WindProtector (wind_protector) VALUES
('NA'),
('FLAPBLAST_2'),
('FLAPBLAST_3');
create table dbo.CarOptions (
options_id int not null primary key -- surrogate key
, car_type varchar(20) not null references CarType (car_type)
, wind_protector varchar(20) not null references WindProtector (wind_protector)
, unique (car_type, wind_protector)
);
insert into dbo.CarOptions (options_id, car_type, wind_protector) VALUES
(1, 'HARD_TOP', 'NA'),
(2, 'CONVERTIBLE', 'FLAPBLAST_3'),
(3, 'CONVERTIBLE', 'FLAPBLAST_2');
create table dbo.Car (
car_guid UNIQUEIDENTIFIER default(newid())
, option_id int not null references CarOptions (options_id)
);
insert dbo.Car (option_id) VALUES
(1),
(2),
(3);
根據需要,您可能希望將Car
和CarOptions
合並到一張表中。
我還建議使用NULL
而不是'NA'
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.