oracle 用PL/SQL语言实现动态查询

6kkfgxo0  于 2023-10-16  发布在  Oracle
关注(0)|答案(2)|浏览(113)

如何在dd/mm/yyyy中使用动态PL/SQL查询获取日期格式?
我尝试了很多方法,但都不起作用。有人能建议正确的方法得到出生日期在下面的格式(dd/mm/yyyy

V_DYNAMICSQL := 'select to_char(a.dat_of_birth) Date_of_birth
from genmst_customer a'

Execute immediate v_dynamicsql;
m0rkklqb

m0rkklqb1#

没有必要使用动态SQL,因为查询没有任何动态内容。你可以选择一个DATE(没有格式),然后当你想显示它时,你可以使用TO_CHAR并提供一个格式模型:

DECLARE
  v_date_of_birth GENMST_CUSTOMER.DAT_OF_BIRTH%TYPE;
BEGIN
  SELECT dat_of_birth
  INTO   v_date_of_birth
  FROM   genmst_customer
  WHERE  id = 1;

  DBMS_OUTPUT.PUT_LINE(TO_CHAR(v_date_of_birth, 'dd/mm/yyyy'));
END;
/

其中,对于样本数据:

CREATE TABLE genmst_customer (id, dat_of_birth) AS
SELECT 1, DATE '1970-01-01' FROM DUAL UNION ALL
SELECT 2, DATE '1980-01-01' FROM DUAL UNION ALL
SELECT 3, DATE '1990-01-01' FROM DUAL UNION ALL
SELECT 4, DATE '2000-01-01' FROM DUAL;

输出:

01/01/1970

fiddle

bqucvtff

bqucvtff2#

to_char本身是不够的-你还应该提供格式模型
样品表:

SQL> desc genmst_customer
 Name                                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 ENAME                                              VARCHAR2(10)
 DAT_OF_BIRTH                                       DATE

SQL> select * from genmst_customer;

ENAME      DAT_OF_BI
---------- ---------
CLARK      09-JUN-81
KING       17-NOV-81
MILLER     23-JAN-82

PL/SQL过程;第5行中的注解格式模型。我只取一行:

SQL> set serveroutput on
SQL> declare
  2    v_dynamicsql varchar2(500);
  3    result       varchar2(20);
  4  begin
  5    v_dynamicsql := q'[select to_char(a.dat_of_birth, 'dd/mm/yyyy')]' ||
  6                     ' from genmst_customer a where rownum = 1';
  7    execute immediate v_dynamicsql into result;
  8    dbms_output.put_line('Result = ' || result);
  9  end;
 10  /
Result = 09/06/1981

PL/SQL procedure successfully completed.

SQL>

**[编辑]**基于您的评论。

如果你想使用alias和refcursor,没问题。下面是一个示例:

SQL> create or replace function f_test
  2    return sys_refcursor
  3  is
  4    rc sys_refcursor;
  5  begin
  6    open rc for select name, to_char(dat_of_birth, 'dd/mm/yyyy') as dob
  7                from genmst_customer
  8                where rownum <= 3;
  9    return rc;
 10  end;
 11  /

Function created.

SQL> select f_test from dual;

F_TEST
--------------------
CURSOR STATEMENT : 1

CURSOR STATEMENT : 1

NAME       DOB
---------- ----------
SMITH      17/12/1980
ALLEN      20/02/1981
WARD       22/02/1981

SQL>

相关问题