Kev*_*vin 22 sql-server ddl check-constraints
我在 SQL Server 中有一个表,用户需要在其中的两列中输入数据。也就是说,两者之一必须输入数据,但同时我不想让用户在两列中输入。它要么是要么,但一个是必须的。
a_h*_*ame 24
您需要使用检查约束:
create table kevin
(
one integer,
other integer,
constraint only_one_value
check ( (one is null or other is null)
and not (one is null and other is null) )
);
Run Code Online (Sandbox Code Playgroud)
这确保至少一列有一个值,而不是两列都有一个值。
如果这些是varchar列,您可能还想检查空值 ( '')。为此,请使用nullif()将值转换为null是否等于函数的第二个参数。
create table kevin
(
one integer,
other integer,
constraint only_one_value
check ( (nullif(one,'') is null or nullif(other,'') is null)
and not (nullif(one,'') is null and nullif(other,'') is null) )
);
Run Code Online (Sandbox Code Playgroud)
像这样吗?
create table #t (col1 int, col2 int)
go
alter table #t with check add
constraint ck_only_one check ((col1 is null and col2 is not null) or (col2 is null and col1 is not null));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11734 次 |
| 最近记录: |