创建IBM DB2 CHECK,使日期大于或等于当前日期

时间:2010-03-02 16:05:29

标签: sql db2 constraints

我正在尝试创建一个具有开始日期的字段的表,我想要检查以确保无法输入今天之前的日期。这是我到目前为止的代码表

CREATE TABLE client_service (
    NHS_num Varchar(10) NOT NULL,
    service_id Integer NOT NULL,
    starting_date Date NOT NULL CHECK(starting_date >= CURDATE()),
    num_weeks Integer NOT NULL CHECK(num_weeks > 0),
    client_contribution Decimal(10,2) NOT NULL CHECK(client_contribution >= 0),
    CONSTRAINT PrimaryKey PRIMARY KEY (
            NHS_num,
            service_id,
            starting_date
    )
);

2 个答案:

答案 0 :(得分:2)

根据CREATE TABLE的documentation

The search-condition cannot contain any of the following (SQLSTATE 42621):
* Subqueries
* XMLQUERY or XMLEXISTS expressions
* Dereference operations or DEREF functions where the scoped reference argument is other than the object identifier (OID) column
* CAST specifications with a SCOPE clause
* Column functions
* Functions that are not deterministic
* Functions defined to have an external action
* User-defined functions defined with either CONTAINS SQL or READS SQL DATA
* Host variables
* Parameter markers
* Special registers
* Global variables
* References to generated columns other than the identity column
* References to columns of type XML (except in a VALIDATED predicate)
* An error tolerant nested-table-expression

因此,正如Leslie建议的那样,正确的方法是使用BEFORE INSERT触发器。

答案 1 :(得分:1)

我认为问题是在检查中使用CURDATE函数。我跑了这个例子:
CREATE TABLE EMP
(ID SMALLINT NOT NULL,
NAME VARCHAR(9),
DEPT SMALLINT CHECK (DEPT BETWEEN 10 AND 100),
JOB CHAR(5) CHECK (JOB IN ('Sales', 'Mgr', 'Clerk')),
HIREDATE DATE,
SALARY DECIMAL(7,2),
COMM DECIMAL(7,2),
PRIMARY KEY (ID),
CONSTRAINT YEARSAL CHECK (YEAR(HIREDATE) >= 1986 OR SALARY > 40500) )

它运作得很好。我把它改成了这个:
CREATE TABLE landrews.EMP
(ID SMALLINT NOT NULL,
NAME VARCHAR(9),
DEPT SMALLINT CHECK (DEPT BETWEEN 10 AND 100),
JOB CHAR(5) CHECK (JOB IN ('Sales', 'Mgr', 'Clerk')),
HIREDATE DATE,
SALARY DECIMAL(7,2),
COMM DECIMAL(7,2),
PRIMARY KEY (ID),
CONSTRAINT YEARSAL CHECK (HIREDATE >= CURDATE() ) )

并且它拒绝了它包含以下错误消息: CHECK条件使用列函数或UDF