最近在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
-------------------
2017-09-14 08:33:17
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, 2009, 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, 2009, 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_AMERICA.ZHS16GBK
[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, 2009, 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
-------------------
2017-09-13 09:41:58
SQL>