在 PLSQL 上添加到列 10 个选项

Adding to a column 10 options on PLSQL

我想添加列,但我的数据库应该有 10 个选项(PL/SQL)。

我的 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>

[编辑] 啊,你把问题搞反了。如果要添加新列并限制有效值的数量,则:

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>