简体   繁体   中英

How can I pass variable to sqlplus script and use same variable as table-prefix in Oracle query?

I am having following sql script namely check_and_create_tbl.sql

DECLARE
t_count NUMBER;

BEGIN
  SELECT count(*) into t_count FROM all_objects WHERE object_name = '&1_EMPLOYEE' AND object_type = 'TABLE';

  if t_count <= 0 then
    execute immediate 'CREATE TABLE ' || &1 || '_EMPLOYEE (
      ID    NUMBER(3)
    , NAME  VARCHAR2(30) NOT NULL
    )';
  end if;
END;

Now I am calling above script in my bash program's function like below.

function exe_orcl {
  exe_command+=("/opt/bin/sqlplus -s <ORCL_USER>/<ORCL_PASS>@(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=<ORCL_HOST>)(PORT=<ORCL_PORT>)))(CONNECT_DATA=(SERVICE_NAME=<ORCL_SNAME>))) ")

  while (( $# > 0 )); do
    exe_command+=("$1")
    shift 1
  done

  echo "SQLPLUS command  =  ${_cmd[@]}"

  "${exe_command[@]}" && { echo "SQLPLUS Success"; } || { echo "SQLPLUS Failed"; }
}

function exe_orcl_sql_file {
  sql_file=$1
  prefix="TBL_SALE"
  shift 1

  exe_orcl << EOF
  whenever oserror exit 9;
  whenever sqlerror exit SQL.SQLCODE;
  SET NEWPAGE NONE
  @${sql_file} ${prefix} ${@};
  exit
  EOF
}

Now in my bash program I try to execute sql file like below.

exe_orcl_sql_file "/tmp/check_and_create_tbl.sql" || { echo "SQLPLUS execution error"; }

I am seeing the log as below.

SQLPLUS command  =  /opt/bin/sqlplus -s XXXX/XXXX@(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=XXXX)(PORT=XXXX)))(CONNECT_DATA=(SERVICE_NAME=XXXX))) 

SQLPLUS Success

But I do not see the TBL_SALE_EMPLOYEE created in Oracle DB, please guide me as to what am i missing here?

You need to remember that the variable is input by sql*plus, you also have to realise that '_' is a valid part of a variable name so you need to clearly point out where the end should be.

DECLARE
t_count NUMBER;

BEGIN
  SELECT count(*) into t_count FROM all_objects WHERE object_name = '&1._EMPLOYEE' AND object_type = 'TABLE';

  if t_count <= 0 then
    execute immediate 'CREATE TABLE  &1._EMPLOYEE (
      ID    NUMBER(3)
    , NAME  VARCHAR2(30) NOT NULL
    )';
  end if;
END;
/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM