如何声明变量并在同一个Oracle SQL脚本中使用它?

时间:2010-08-25 09:03:12

标签: sql oracle variables declaration

我想编写可重用的代码,需要在开头声明一些变量并在脚本中重用它们,例如:

DEFINE stupidvar = 'stupidvarcontent';

SELECT stupiddata
FROM stupidtable
WHERE stupidcolumn = &stupidvar;

如何声明变量并在后面的语句中重用它,例如使用SQLDeveloper。


尝试

  • 使用DECLARE部分并在BEGINEND;中插入以下SELECT语句。使用&stupidvar
  • 访问变量
  • 使用关键字DEFINE并访问变量。
  • 使用关键字VARIABLE并访问变量。

但我在尝试期间遇到各种错误(未绑定变量,语法错误,预期SELECT INTO ...)。

10 个答案:

答案 0 :(得分:123)

在SQL * Plus脚本中有几种声明变量的方法。

首先是使用VAR。为VAR分配值的机制是使用EXEC调用:

SQL> var name varchar2(20)
SQL> exec :name := 'SALES'

PL/SQL procedure successfully completed.

SQL> select * from dept
  2  where dname = :name
  3  /

    DEPTNO DNAME          LOC
---------- -------------- -------------
        30 SALES          CHICAGO

SQL>

当我们想要调用具有OUT参数或函数的存储过程时,VAR特别有用。

Alternativley我们可以使用替换变量。这些对于交互模式很有用:

SQL> accept p_dno prompt "Please enter Department number: " default 10
Please enter Department number: 20
SQL> select ename, sal
  2  from emp
  3  where deptno = &p_dno
  4  /
old   3: where deptno = &p_dno
new   3: where deptno = 20

ENAME             SAL
---------- ----------
CLARKE            800
ROBERTSON        2975
RIGBY            3000
KULASH           1100
GASPAROTTO       3000

SQL>

当我们编写一个调用其他脚本的脚本时,预先定义变量会很有用:

SQL> def p_dno = 40
SQL> select ename, sal
  2  from emp
  3  where deptno = &p_dno
  4  /
old   3: where deptno = &p_dno
new   3: where deptno = 40

no rows selected

SQL>

最后是匿名的PL / SQL块。如您所见,我们仍然可以交互地为声明的变量赋值:

SQL> set serveroutput on size unlimited
SQL> declare
  2      n pls_integer;
  3      l_sal number := 3500;
  4      l_dno number := &dno;
  5  begin
  6      select count(*)
  7      into n
  8      from emp
  9      where sal > l_sal
 10      and deptno = l_dno;
 11      dbms_output.put_line('top earners = '||to_char(n));
 12  end;
 13  /
Enter value for dno: 10
old   4:     l_dno number := &dno;
new   4:     l_dno number := 10;
top earners = 1

PL/SQL procedure successfully completed.

SQL>

答案 1 :(得分:23)

如果它是char变量,请尝试使用双引号:

DEFINE stupidvar = "'stupidvarcontent'";

DEFINE stupidvar = 'stupidvarcontent';

SELECT stupiddata  
FROM stupidtable  
WHERE stupidcolumn = '&stupidvar'

UPD:

SQL*Plus: Release 10.2.0.1.0 - Production on Wed Aug 25 17:13:26 2010

Copyright (c) 1982, 2005, Oracle.  All rights reserved.

SQL> conn od/od@etalon
Connected.
SQL> define var = "'FL-208'";
SQL> select code from product where code = &var;
old   1: select code from product where code = &var
new   1: select code from product where code = 'FL-208'

CODE
---------------
FL-208

SQL> define var = 'FL-208';
SQL> select code from product where code = &var;
old   1: select code from product where code = &var
new   1: select code from product where code = FL-208
select code from product where code = FL-208
                                      *
ERROR at line 1:
ORA-06553: PLS-221: 'FL' is not a procedure or is undefined

答案 2 :(得分:14)

在PL / SQL v.10中

keyword declare用于声明变量

DECLARE stupidvar varchar(20);

指定一个值,您可以在声明

时设置它
DECLARE stupidvar varchar(20) := '12345678';

或者在您使用INTO语句的变量中选择一些内容,但是您需要在BEGINEND中包装语句,同时您还需要确保只返回单个值,别忘了用分号。

所以完整的陈述将在下面出现:

DECLARE stupidvar varchar(20);
BEGIN
    SELECT stupid into stupidvar FROM stupiddata CC 
    WHERE stupidid = 2;
END;

您的变量只能在BEGINEND内使用,因此如果您想使用多个变量,则必须执行多个BEGIN END包装

DECLARE stupidvar varchar(20);
BEGIN
    SELECT stupid into stupidvar FROM stupiddata CC 
    WHERE stupidid = 2;

    DECLARE evenmorestupidvar varchar(20);
    BEGIN
        SELECT evenmorestupid into evenmorestupidvar FROM evenmorestupiddata CCC 
        WHERE evenmorestupidid = 42;

        INSERT INTO newstupiddata (newstupidcolumn, newevenmorestupidstupidcolumn)
        SELECT stupidvar, evenmorestupidvar 
        FROM dual

    END;
END;

希望这能节省你一些时间

答案 3 :(得分:5)

如果要声明日期,然后在SQL Developer中使用它。

DEFINE PROPp_START_DT = TO_DATE('01-SEP-1999')

SELECT * 
FROM proposal 
WHERE prop_start_dt = &PROPp_START_DT

答案 4 :(得分:3)

只想添加 Matas '答案。 也许这很明显,但我已经搜索了很长时间才发现变量只能在BEGIN-END 构造中访问,所以如果你以后需要在某些代码中使用它,你需要将此代码放入BEGIN-END块

请注意,这些块可以嵌套

DECLARE x NUMBER;
  BEGIN
    SELECT PK INTO x FROM table1 WHERE col1 = 'test';

    DECLARE y NUMBER;
    BEGIN
    SELECT PK INTO y FROM table2 WHERE col2 = x;

    INSERT INTO table2 (col1, col2)
      SELECT y,'text'
      FROM dual
      WHERE exists(SELECT * FROM table2);
    COMMIT;
  END;
END;

答案 5 :(得分:3)

问题是在脚本中使用变量意味着它将在SQL * Plus中使用。

问题是您错过了引号,Oracle无法将值解析为数字。

SQL> DEFINE num = 2018
SQL> SELECT &num AS your_num FROM dual;
old   1: SELECT &num AS your_num FROM dual
new   1: SELECT 2018 AS your_num FROM dual

  YOUR_NUM
----------
      2018

Elapsed: 00:00:00.01

由于自动类型转换(或其他任何调用),此示例工作正常。

如果通过在SQL * Plus中键入DEFINE进行检查,则会显示num变量为CHAR。

SQL>define
DEFINE NUM             = "2018" (CHAR)

在这种情况下,这不是问题,因为Oracle可以处理将字符串解析为数字(如果它是有效数字)。

当字符串无法解析为数字时,Oracle无法处理它。

SQL> DEFINE num = 'Doh'
SQL> SELECT &num AS your_num FROM dual;
old   1: SELECT &num AS your_num FROM dual
new   1: SELECT Doh AS your_num FROM dual
SELECT Doh AS your_num FROM dual
       *
ERROR at line 1:
ORA-00904: "DOH": invalid identifier

有了引用,所以不要强迫Oracle解析数字,也没关系:

17:31:00 SQL> SELECT '&num' AS your_num FROM dual;
old   1: SELECT '&num' AS your_num FROM dual
new   1: SELECT 'Doh' AS your_num FROM dual

YOU
---
Doh

所以,回答原来的问题,应该像这样的样本:

SQL> DEFINE stupidvar = 'X'
SQL>
SQL> SELECT 'print stupidvar:' || '&stupidvar'
  2  FROM dual
  3  WHERE dummy = '&stupidvar';
old   1: SELECT 'print stupidvar:' || '&stupidvar'
new   1: SELECT 'print stupidvar:' || 'X'
old   3: WHERE dummy = '&stupidvar'
new   3: WHERE dummy = 'X'

'PRINTSTUPIDVAR:'
-----------------
print stupidvar:X

Elapsed: 00:00:00.00

还有另一种方法可以使用查询列值在SQL * Plus中存储变量。

COL [UMN]具有 new_value 选项,可以按字段名称查询值。

SQL> COLUMN stupid_column_name new_value stupid_var noprint
SQL> SELECT dummy || '.log' AS stupid_column_name
  2  FROM dual;

Elapsed: 00:00:00.00
SQL> SPOOL &stupid_var.
SQL> SELECT '&stupid_var' FROM DUAL;
old   1: SELECT '&stupid_var' FROM DUAL
new   1: SELECT 'X.log' FROM DUAL

X.LOG
-----
X.log

Elapsed: 00:00:00.00
SQL>SPOOL OFF;

如您所见,X.log值已设置为 stupid_var 变量,因此我们可以在当前目录中找到一个X.log文件,其中包含一些日志。

答案 6 :(得分:2)

这是你的答案:

DEFINE num := 1;       -- The semi-colon is needed for default values.
SELECT &num FROM dual;

答案 7 :(得分:0)

在Toad中,我使用此作品:

declare 
    num number;
begin 
    ---- use 'select into' works 
    --select 123 into num from dual;

    ---- also can use :=
    num := 123;
    dbms_output.Put_line(num);
end;

然后将值打印到DBMS Output窗口。

参考herehere2

答案 8 :(得分:0)

有时,您需要使用宏变量而不要求用户输入值。通常,这必须使用可选的脚本参数来完成。以下代码功能齐全

column 1 noprint new_value 1
select '' "1" from dual where 2!=2;
select nvl('&&1', 'VAH') "1" from dual;
column 1 clear
define 1

在rdbms / sql目录中找到了类似的代码。

答案 9 :(得分:0)

如果您只需要指定一次参数并将其复制到多个位置,则一种可能的方法是执行以下操作:

SELECT
  str_size  /* my variable usage */
  , LPAD(TRUNC(DBMS_RANDOM.VALUE * POWER(10, str_size)), str_size, '0') rand
FROM
  dual  /* or any other table, or mixed of joined tables */
  CROSS JOIN (SELECT 8 str_size FROM dual);  /* my variable declaration */

此代码生成由8个随机数字组成的字符串。

请注意,我创建了一种名为str_size的别名,其中包含常量8。交叉联接将在查询中多次使用。