最近在ORACLE里面设置NLS_DATE_FORMAT日期时间格式时遇到了一些问题,顺便整理一下。以防以后忘记时,能顺速翻阅。
1、在会话级别设置nls_date_format对应的日期格式。
使用alter session set nls_date_format='xxxx'设置只会影响当前会话的。这个对所有工具(SQL*Plus、SQL Developer)都能生效。
SQL> select sysdate from dual;
SYSDATE
---------
14-SEP-17
SQL> alter session set nls_date_format='yyyy-mm-dd hh24:mi:ss';
Session altered.
SQL> select sysdate from dual;
SYSDATE
-------------------
SQL>
2、如果只是SQL*Plus,可以在SQL*Plus的环境变量设置文件login.sql或glogin.sql中来设置。
SQL*Plus启动的时候首先会先运行glogin.sql脚本,然后查找当前目录下是否存在login.sql文件,如果找到则运行该脚本,如果当前目录不存在login.sql.则查找是否设置了SQLPATH环境变量,找到了就会去执行该环境变量路径下的login.sql脚本,否则则会停止继续查找。 glogin.sql文件位于$ORACLE_HOME/sqlplus/admin下.可以在glogin.sql文件下增加一条语句alter session set nls_date_format='yyyy-mm-dd hh24:mi:ss';
3、修改数据库的参数,需要重启数据库后生效
SQL> show parameter nls_date_format;
NAME TYPE VALUE
nls_date_format string
SQL> alter system set nls_date_format='yyyy-mm-dd hh24:mi:ss' scope=spfile;
System altered.
SQL>
这个是全局的,有时候影响非常大,所以必须格外小心,要确保不影响各个系统和应用的前提下修改!
4、修改Linux环境变量,在环境变量中设置日期格式。
注意:环境变量NLS_DATE_FORMAT必须和NLS_LANG一起设置,否则不会生效(这个才是总结这篇文章的初衷,以前一直没有注意这个问题)。可以直接在会话窗口使用export或.bash_profile配置文件(全局应用)设置。
下面我们来测试一下看看,如下所示:
[oracle@DB-Server ~]$ sqlplus / as sysdba
SQL*Plus: Release 11.2.0.1.0 Production on Wed Sep 13 09:40:48 2017
Copyright (c) 1982, 2017, Oracle. All rights reserved.
Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options
SQL> select sysdate from dual;
SYSDATE
---------
13-SEP-17
SQL> exit
Disconnected from Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options
[oracle@DB-Server ~]$ export NLS_DATE_FORMAT='yyyy-mm-dd hh24:mi:ss';
[oracle@DB-Server ~]$ sqlplus / as sysdba
SQL*Plus: Release 11.2.0.1.0 Production on Wed Sep 13 09:41:22 2017
Copyright (c) 1982, 2017, Oracle. All rights reserved.
Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options
SQL> select sysdate from dual;
SYSDATE
---------
13-SEP-17
SQL> exit
Disconnected from Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options
[oracle@DB-Server ~]$ export NLS_LANG=AMERICAN
[oracle@DB-Server ~]$ sqlplus / as sysdba
SQL*Plus: Release 11.2.0.1.0 Production on Wed Sep 13 09:41:50 2017
Copyright (c) 1982, 2017, Oracle. All rights reserved.
Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options
SQL> select sysdate from dual;
SYSDATE
-------------------
SQL>