声明变量并在查询oracle中使用它们

qzwqbdag  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(358)

我正在进行数据迁移,在oracle11g中转换sybase查询,在过去的两天里我一直在做这件事

@Declare @myDate Datetime
Select @myDate = workingDate from MyTable

然后,很少有sql语句在where子句中使用varaible mydate
对于前

Select * form table1 
join table1 on table1.id = table.id
join table1 on table1.id =  mytable.id
where mytable.workingDate = my_date

//最后,我想声明一个变量,该变量将从select子句中获取其值,并在复杂查询的进一步sql语句中使用它
我希望在oracle11g中实现同样的功能,而不增加任何复杂性
我是甲骨文的新手,需要你的帮助。

baubqpgj

baubqpgj1#

您使用的是sqlplus吗:我认为您不能声明sqlplus时间戳变量。
请尝试使用varchar2变量并转换为时间戳:

SQL> select banner from v$version where rownum=1;

BANNER
--------------------------------------------------------------------------------
Oracle Database 19c Enterprise Edition Release 19.0.0.0.0 - Production

SQL> variable ko timestamp;
Usage: VAR[IABLE] [ <variable> [ NUMBER | CHAR | CHAR (n [CHAR|BYTE]) |
            VARCHAR2 (n [CHAR|BYTE]) | NCHAR | NCHAR (n) |
            NVARCHAR2 (n) | CLOB | NCLOB | BLOB | BFILE
            REFCURSOR | BINARY_FLOAT | BINARY_DOUBLE ] ]
SQL> --
SQL> variable my_date varchar2(50) ;
SQL> begin
  2  select workingDate  into :my_date from MyTable;
  3  end;
  4  /

PL/SQL procedure successfully completed.

SQL> print my_date;

MY_DATE
------------------------------
20-JUN-20 10.55.55.264286 AM

SQL> print :my_date;

MY_DATE
------------------------------
20-JUN-20 10.55.55.264286 AM

SQL> --
SQL> select * from mytable;

WORKINGDATE
------------------------------
20-JUN-20 10.55.55.264286 AM

SQL> select workingDate  from MyTable where workingDate = to_timestamp(:my_date, 'DD-MON-YY HH.MI.SSXFF AM');

WORKINGDATE
------------------------------
20-JUN-20 10.55.55.264286 AM

SQL>
yyhrrdl8

yyhrrdl82#

variable 不支持日期或时间戳。最后的查询也应该使用 :my_date (表示主机变量),而不是 my_date .
如果目标是使用前一步中填充的变量填充表,那么可以对整个任务使用pl/sql,例如。

declare
    myDate date;
begin
    select some_col into myDate from wherever;

    insert into target_table (col1, col2, col2)
    select x, y, z
    from   source_table
    where  business_date = myDate;
end;

或者更好的是,定义pl/sql包来封装处理逻辑。
关于您发布的代码,从oracle 12.1开始,您可以在pl/sql中声明一个ref游标,并让sql*plus等客户机调用该块并打印结果:

declare
    my_date timestamp;
    results sys_refcursor;
begin
    select systimestamp into my_date
    from   dual;

    open results for
        select my_date as my_date from dual;

    dbms_sql.return_result(results);
end;
/
PL/SQL procedure successfully completed.

ResultSet #1

MY_DATE
---------------------------------------------------------------------------
20-JUN-20 10.02.29.130000000

1 row selected.

对于早期的oracle版本,您仍然必须在sql*plus中将ref cursor声明为主机变量:

set autoprint on

var results refcursor

declare
    my_date timestamp;
begin
    select systimestamp into my_date
    from   dual;

    open :results for
        select my_date as my_date from dual;
end;
/

(或 set autoprint off 然后 print results 明确地。)
但是我不懂java,所以我不知道上面的方法是否适用于您的环境。

相关问题