SQL Server,检查多列可为空性的约束

时间:2019-03-23 04:27:35

标签: sql-server

在SQL Server中,有column acolumn b列。仅当存在column a的值时,column b不应为null。您可以在插入创建脚本中的值之前执行此操作吗?我们该怎么做?

2 个答案:

答案 0 :(得分:0)

使用这种CHECK约束:

USE tempdb;
CREATE TABLE test
(
    col1 INT,
    col2 INT
);

ALTER TABLE test
ADD CONSTRAINT ck_combined CHECK 
(
    (
        col1 IS NOT NULL
        AND col2 IS NOT NULL
    )
    OR (col1 IS NULL)
);

-- (1 row affected)
INSERT INTO test VALUES (NULL, NULL);

--Msg 547, Level 16, State 0, Line 10
--The INSERT statement conflicted with the CHECK constraint "ck_combined". The conflict occurred in database "tempdb", table "dbo.test".
INSERT INTO test VALUES (1, NULL);

答案 1 :(得分:0)

是的,可以使用检查约束

尝试-

create table myTable (ID int identity(1,1)
                        , a int
                        , b int 
                        )
go

ALTER TABLE myTable 
ADD CONSTRAINT ck_BNotNull 
CHECK ( 
        (A is not null and b is not null) 
        or  (A is null)

        )

   go

-不允许

  insert into myTable
   (a,b)
   values
   (1,null)

-允许

insert into myTable
   (a,b)
   values
   (null,null)

-允许

 insert into myTable
   (a,b)
   values
   (null,1)