0

Possible Duplicate:
One of the column between two columns should be NOT NULL. How to enforce it in schema?

I have a table with 5 null able fields and every record must have a value for one of those fields. Can I enforce user to enter value in minimum one of many nullable fields in SQL? Thanx

4

3 回答 3

5

是的,你可以,使用CHECK约束

CREATE TABLE test
(
  id INT,
  val1 VARCHAR(32),
  val2 VARCHAR(32),
  val3 VARCHAR(32),
  val4 VARCHAR(32),
  val5 VARCHAR(32),
  CHECK (COALESCE(val1,val2,val3,val4,val5) IS NOT NULL)
);

...将要求至少一个 val1-val5 不为空。

于 2013-01-13T08:29:32.293 回答
4
ADD CONSTRAINT chkAnyNotNULL CHECK (col1 IS NOT NULL OR Col2 IS NOT NULL OR ....);
于 2013-01-13T08:29:49.660 回答
1

是的。使用CHECK CONSTRAINT;

USE tempdb
GO

IF OBJECT_ID('tempdb.dbo.MyTable') IS NOT NULL DROP TABLE MyTable

CREATE TABLE MyTable
(
    Col1    INT NULL,
    Col2    INT NULL,
    Col3    INT NULL,
    Col4    INT NULL,
    Col5    INT NULL,
    CONSTRAINT OneNonNull CHECK (COALESCE(Col1, Col2, Col3, Col4, Col5) IS NOT NULL)
)
GO

INSERT INTO MyTable
SELECT 1,2,3,4,5
GO

INSERT INTO MyTable
SELECT 1,NULL, NULL, NULL, NULL
GO

INSERT INTO MyTable
SELECT NULL, NULL, NULL, NULL, NULL
GO

SELECT *
FROM MyTable
于 2013-01-13T08:36:32.140 回答