在Oracle中创建查询以替换变量

时间:2016-01-17 14:37:57

标签: sql oracle

我有以下问题:

SELECT c.accountid, c.accountnum
FROM account o, account@oltp c
WHERE o.accountid = c.accountid and c.date > sysdate;

我已登录数据中心'数据库并从c数据中心的数据库中提取详细信息,我需要一个简单的PL / SQL查询,如下所示:

declare
variable

begin
statements...
....

end

我不需要任何程序或功能。

我想要做的就是将account@oltp csysdate替换为变量。

select c.accountid, c.accountnum
from account o, (variable)
where o.accountid = c.accountid and c.date > (variable);

我该怎么做?

1 个答案:

答案 0 :(得分:0)

Oracle安装程序

CREATE TABLE accounts ( accountid, accountnum ) AS
  SELECT LEVEL, LEVEL FROM DUAL CONNECT BY LEVEL < 11;

CREATE TABLE accounts2 ( accountid, accountnum, "date" ) AS
  SELECT 2*LEVEL, 2*LEVEL, SYSDATE + 1 FROM DUAL CONNECT BY LEVEL < 6;

PL / SQL匿名阻止

SET SERVEROUTPUT ON; 
/
DECLARE
  TYPE acc_cursor IS REF CURSOR;
  table_name  VARCHAR2(100) := 'accounts2';
  datetime    DATE          := SYSDATE;
  v_cursor    acc_cursor;
  v_accid     NUMBER;
  v_accnum    NUMBER;
BEGIN
  OPEN v_cursor FOR
    'SELECT c.accountid, c.accountnum '
     || 'FROM   accounts o '
     || 'INNER JOIN ' || table_name || ' c '
     || 'ON ( o.accountid = c.accountid ) '
     || 'WHERE c."date" > :dt'
  USING datetime;

  -- Fetch rows from result set one at a time:
  LOOP
    FETCH v_cursor INTO v_accid, v_accnum;
    EXIT WHEN v_cursor%NOTFOUND;

    DBMS_OUTPUT.PUT_LINE( v_accid || ' - ' || v_accnum );
  END LOOP;

  CLOSE v_cursor;
END;
/