【问题标题】:I need a check constraint on two columns, at least one must be not null我需要对两列进行检查约束,至少一列不能为空
【发布时间】:2014-11-23 23:55:33
【问题描述】:

我在 SQL Server 中有一个包含两个数字列的表。必须填写这些数字字段中的至少一个。如何编写检查约束来验证这一点?

【问题讨论】:

标签: sql sql-server-2012


【解决方案1】:

这可以通过一个检查约束来完成,该约束验证空值并将结果与​​ or 匹配

create table #t (i int
               , j int
               , constraint chk_null check (i is not null or j is not null))

以下是测试用例

insert into #t values (null, null) --> error
insert into #t values (1, null) --> ok
insert into #t values (null, 1) --> ok
insert into #t values (1, 1) --> ok

【讨论】:

    【解决方案2】:

    迟到的答案,但这里是 Sql Server 的解决方案,可以检查任意数量的列:

    CONSTRAINT CK_one_is_not_null CHECK (COALESCE(col1, col2, col3) IS NOT NULL )
    

    【讨论】:

    • 如果列具有相同的数据类型,则此方法有效。否则系统将尝试转换以检查此约束
    猜你喜欢
    • 2014-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-23
    • 2016-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多