oracle通过shell脚本改变序列& SQLPLUS

时间:2017-05-25 08:27:59

标签: oracle shell variables sqlplus

我正致力于在shell脚本中通过sqlplus更改序列。 我要做的是获取表的max seq_no,在v_increment_num中设置值,并通过v_increment_num增加序列。但是当alter语句运行时会出错。

脚本如下所示。

echo start load_my_adm_user.sh

sqlplus myId/myPassword <<EOF

set echo on
set time on
set timing on
set serveroutput on
spool TB_MY_ADM_USER.log

var v_increment_num varchar2(1000);

SELECT MAX(SEQ_NO) INTO :v_increment_num FROM TB_MY_ADM_USER;
alter sequence mydb.SQ_ADM_USER increment by v_increment_num;
select mydb.SQ_ADM_USER.nextval from dual;
alter sequence mydb.SQ_ADM_USER increment by 1;

spool off
EOF
exit

和运行结果(TB_MY_ADM_USER.log)如下:

07:01:23 SQL> SELECT MAX(SEQ_NO) INTO :v_increment_num FROM TB_MY_ADM_USER;

MAX(SEQ_NO)
-----------
          4

Elapsed: 00:00:00.00
07:01:23 SQL>
07:01:23 SQL> alter sequence mydb.SQ_ADM_USER increment by v_increment_num;
alter sequence mydb.SQ_ADM_USER increment by v_increment_num
                                                  *
ERROR at line 1:
ORA-01722: invalid number


Elapsed: 00:00:00.00
07:01:23 SQL>
07:01:23 SQL> select mydb.SQ_ADM_USER.nextval from dual;

   NEXTVAL
----------
        19

Elapsed: 00:00:00.02
07:01:23 SQL> alter sequence mydb.SQ_ADM_USER increment by 1;

Sequence altered.

Elapsed: 00:00:00.02

我究竟做错了什么? 提前谢谢。

1 个答案:

答案 0 :(得分:2)

你几乎所有东西都是正确的,只需要记住DDL语句,即alter sequence,也不适用于绑定变量。其中,我的意思是绑定变量,就是您的v_increment_num

如果您将使用SQL * Plus,那么请尝试使用自己的替换“变量”,即“&符号” - 变量......

echo start load_my_adm_user.sh

sqlplus myId/myPassword <<EOF

set echo on
set time on
set timing on
set serveroutput on
spool TB_MY_ADM_USER.log

-- do not do...
-- var v_increment_num varchar2(1000);
-- do instead...
column max_seq_no new_val v_increment_num
-- note: this makes all MAX_SEQ_NO column values from all subsequent SELECTs to be stored in the &V_INCREMENT_NUM variable

-- do not do...
-- SELECT MAX(SEQ_NO) INTO :v_increment_num FROM TB_MY_ADM_USER;
-- do instead...
SELECT MAX(SEQ_NO) as max_seq_no FROM TB_MY_ADM_USER;
-- note: at this point, you will have your MAX(SEQ_NO) value stored in your &V_INCREMENT_NUM variable

-- do not do...
-- alter sequence mydb.SQ_ADM_USER increment by v_increment_num;
-- do instead...
alter sequence mydb.SQ_ADM_USER increment by &v_increment_num;

select mydb.SQ_ADM_USER.nextval from dual;
alter sequence mydb.SQ_ADM_USER increment by 1;

spool off
EOF
exit

注意:我没有尝试过这个特定的代码,只是直接写在这里,所以它可能在第一次尝试时没有工作,但我们会在以后解决这个可能性。