Search code examples
sqloracle-databasedatestored-proceduresoracle12c

Change from Default Date to preferred date in this DBMS_SQL?


This code is from the proposed solution: https://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:9541646100346616701

My query is 'select * from table'

The second column is a DATE and this routine writes it as appears in my IDE session ('DD-MON-YY');

How can I report the values in DATE columns to 'YYYY-MM-DD'?

procedure clob_maker(p_query varchar2) is

      l_theCursor     integer default dbms_sql.open_cursor;
      l_columnValue   varchar2(4000);
      l_status        integer;
      l_descTbl       dbms_sql.desc_tab;
      l_colCnt        number;
      n number := 0;

      l_data clob;
  begin
      dbms_sql.parse(  l_theCursor,  p_query, dbms_sql.native );
      dbms_sql.describe_columns( l_theCursor, l_colCnt, l_descTbl );

      for i in 1 .. l_colCnt loop
          dbms_sql.define_column(l_theCursor, i, l_columnValue, 4000);
      end loop;

      l_status := dbms_sql.execute(l_theCursor);

      while ( dbms_sql.fetch_rows(l_theCursor) > 0 ) loop
          for i in 1 .. l_colCnt loop 
              dbms_sql.column_value( l_theCursor, i, l_columnValue );
              --dbms_output.put_line(l_columnValue);  --this puts every column on a separate line
                l_data := l_data || l_columnValue ||',';
          end loop;
            dbms_output.put_line(l_data);
          n := n + 1;
      end loop;
      --dbms_output.put_line(l_data);
  end  clob_maker;

clob_maker('select * from mlb_catcher_birthdays fetch first 10 rows only');

Solution

  • The default format in which dates are represented is controlled by NLS parameter ns_date_format. You can just change this parameter at session level:

    alter session set nls_date_format = 'YYYY-MM-DD';
    

    You could also use TO_CHAR(), with the same format specifier as second argument - but this does not fit very well to your use case, since you would then need to check the datatype of each column before printing its value.