如何制作带有替换变量的INSERT并在SUBSTR上使用该变量值?

问题描述 投票:0回答:1

我有这个查询。它的作用是要求我提供&last_name&first_name的值,并将这些值用于SUBSTR,但是除非我随后使用UNDEFINE variable,否则它将存储该值。

INSERT INTO my_employee (id, last_name, first_name, userid, salary)
VALUES(3, '&&last_name', '&&first_name', 
LOWER(SUBSTR('&first_name', 1, 1)||SUBSTR('&last_name', 1, 7)), 1100);

UNDEFINE last_name
UNDEFINE first_name;

我想要做的是让它每次运行查询时都要求我提供last_namefirst_name的值,并将该值用于SUBSTR串联,因此我不必使用UNDEFINE,并且可以根据需要自由地重复使用该查询。

谢谢您的帮助。 :)

oracle insert oracle-sqldeveloper substitution substr
1个回答
0
投票

删除双“&”号;如果您在整个查询中分布的变量相同,则可以使用它们,这样就不必一遍又一遍地输入相同的值。

如果使用一次,则只能使用一个&号。

比较!

SQL> select &deptno                                --> 1st
  2  from dept
  3  where deptno = &deptno or &deptno is null;    --> 2nd and 3rd
Enter value for deptno: 10                         --> asked 1st time
old   1: select &deptno
new   1: select 10
Enter value for deptno: 10                         --> asked 2nd time
Enter value for deptno: 10                         --> asked 3rd time
old   3: where deptno = &deptno or &deptno is null
new   3: where deptno = 10 or 10 is null

        10
----------
        10

vs。

SQL> select &deptno                                --> 1st
  2  from dept
  3  where deptno = &&deptno or &&deptno is null;  --> 2nd and 3rd
Enter value for deptno: 10
old   1: select &&deptno                           --> asked only once
new   1: select 10
old   3: where deptno = &&deptno or &&deptno is null    --> reused here, without asking
new   3: where deptno = 10 or 10 is null

        10
----------
        10

SQL>

完成后,您必须undefine个变量,否则再次运行查询时将使用相同的值。

我不认为您可以做您想做的事-只需询问一次(即&&所做的事情),而不必undefine这些变量。解决方法?切换到将接受两个参数的存储过程。


[编辑]

嗯,声明变量怎么样?有帮助吗?查看示例:

SQL> var par_deptno number

SQL> exec :par_deptno := 10;

PL/SQL procedure successfully completed.

SQL> select :par_deptno, substr(:par_deptno, 1, 1) sub
  2  from dept
  3  where deptno = :par_deptno or :par_deptno is null;

:PAR_DEPTNO S
----------- -
         10 1

SQL>

如果需要其他值,请再次输入

SQL> exec :par_deptno := 30;
© www.soinside.com 2019 - 2024. All rights reserved.