对于我的学期项目,我们正在创建自己的数据库。我目前正在创建数据库和表。我在Microsoft SQL Server Management Studio中使用SQL。
如果在Type列中选择Beds, Baths, Sqft
,我想使列Lot/Land
只为NULL(如果选择了任何其他选项,则它必须为NOT NULL)。
CREATE TABLE Property(
PropertyID int IDENTITY(1,1) PRIMARY KEY,
StreetAddress1 varchar(n) NOT NULL,
StreetAddress2 varchar(n) NULL,
City varchar(n) NOT NULL,
State varchar(2) NOT NULL,
Type varhar(#) NOT NULL CHECK (Type IN 'Single Family', 'Apartment', 'Condo', 'Townhome', 'Manufactured','Lot/Land'),
Beds varchar(2) NULL,
Baths decimal(3,1) NULL,
Sqft varchar(5) NULL,
Acreage decimal(10,2) NOT NULL)
解决方案需要在ALTER函数中,因为我现在正在创建表。
提前致谢!
答案 0 :(得分:5)
您需要单独的check
约束:
CREATE TABLE Property (
PropertyID int IDENTITY(1,1) PRIMARY KEY,
StreetAddress1 varchar(n) NOT NULL,
StreetAddress2 varchar(n) NULL,
City varchar(n) NOT NULL,
State varchar(2) NOT NULL,
Type varchar(32) NOT NULL CHECK (Type IN 'Single Family', 'Apartment', 'Condo', 'Townhome', 'Manufactured', 'Lot/Land'),
Beds varchar(2) NULL,
Baths decimal(3,1) NULL,
Sqft varchar(5) NULL,
Acreage decimal(10,2) NOT NULL
constraint chk_property_lotland
check ( (type = 'Lot/Land' and Beds is null and Baths is null and Sqft is null) or
(type <> 'Lot/Land' and Beds is not null and Baths is not null and Sqft is not null)
)
);