我目前正在使用Oracle SQL,并且试图将整数数据类型限制为仅接受值0和1(无论是否为活动项)。
这是我目前拥有的:
CREATE TABLE ACTIVE_EX (
ACTIVE int NOT NULL
CONSTRAINT check_active_ind CHECK (ACTIVE = 0 OR ACTIVE = 1)
);
SELECT * FROM ACTIVE_EX;
INSERT INTO ACTIVE_EX(ACTIVE)values(2);
当我输入此命令并运行Select * from ACTIVE_EX
行时,值2仍将正确输入表中。
答案 0 :(得分:2)
怎么样?
SQL> create table test
2 (active int not null
3 constraint ch_active check (active in (0, 1))
4 );
Table created.
SQL>
SQL> insert into test values (-1);
insert into test values (-1)
*
ERROR at line 1:
ORA-02290: check constraint (SCOTT.CH_ACTIVE) violated
SQL> insert into test values (2);
insert into test values (2)
*
ERROR at line 1:
ORA-02290: check constraint (SCOTT.CH_ACTIVE) violated
SQL> insert into test values (100);
insert into test values (100)
*
ERROR at line 1:
ORA-02290: check constraint (SCOTT.CH_ACTIVE) violated
SQL> insert into test values (0.3);
1 row created.
SQL> insert into test values (1.2);
1 row created.
SQL> insert into test values (3.8);
insert into test values (3.8)
*
ERROR at line 1:
ORA-02290: check constraint (SCOTT.CH_ACTIVE) violated
SQL> select * From test;
ACTIVE
----------
0
1
SQL>
如您所见,可以输入0到1之间的十进制值,但是会四舍五入,因此最终结果仍为0或1。