问题描述
我想添加列,但它应该是我的数据库 (PL/sql) 的 10 个选项。
我的SQL查询是这样的:
ALTER TABLE mytable
ADD NEWCOL
你认为这行得通吗?
解决方法
我不必思考,我知道这行不通。
SQL> INSERT_INTO MYTABLE
2 (MYNEW_COL)
3 VALUES
4 (1,2,3,4,5,6,7,8,9,10);
INSERT_INTO MYTABLE
*
ERROR at line 1:
ORA-00900: invalid SQL statement
如果您想准确插入这些值,请使用行生成器:
SQL> insert into mytable (mynew_col)
2 select level from dual
3 connect by level <= 10;
10 rows created.
SQL> select * from mytable;
MYNEW_COL
----------
1
2
3
4
5
6
7
8
9
10
10 rows selected.
SQL>
否则,寻找其他有效的方法来做到这一点,例如
SQL> insert into mytable (mynew_col)
2 select 1 from dual union all
3 select 2 from dual union all
4 select 3 from dual;
3 rows created.
或
SQL> insert all
2 into mytable (mynew_col) values (1)
3 into mytable (mynew_col) values (2)
4 into mytable (mynew_col) values (3)
5 select * from dual;
3 rows created.
SQL>
[EDIT] 啊,你把问题颠倒了。如果要添加新列并限制有效值的数量,则:
SQL> alter table mytable add newcol number;
Table altered.
SQL> alter table mytable add constraint
2 ch_col check (newcol between 1 and 10);
Table altered.
测试:
SQL> update mytable set newcol = 0;
update mytable set newcol = 0
*
ERROR at line 1:
ORA-02290: check constraint (SCOTT.CH_COL) violated
SQL> update mytable set newcol = 11;
update mytable set newcol = 11
*
ERROR at line 1:
ORA-02290: check constraint (SCOTT.CH_COL) violated
SQL> update mytable set newcol = 2;
16 rows updated.
SQL>