如何格式化 SQL 中的当前日期和时间,但只包含时间本身?

How to format the current date and time in SQL but to only include the time by itself?

我不确定如何将 'default sysdate' 格式化为只有 运行 时的时间位?

因此输出将是不带日期的当前时间“15:20:52”。

我正在使用 sql plus。

创建 table 时,像这样:

create table timeslot
(
tsdate default sysdate not null,
tstime default sysdate not null)

如果您使用的是 MS SQL,请尝试以下操作-

SELECT GETDATE() AS INPUT,CONVERT(VARCHAR(10), GETDATE(), 108) AS EXPECTED_OUTPUT;

使用 SQL 服务器:

select convert(varchar, getdate(), 8)

SQLPLUS 标签表示 "Oracle".

由于 Oracle 不提供 "time" 数据类型,您将使用单列:

SQL> create table timeslot
  2    (id   number    primary key,
  3     ts   date      default sysdate not null
  4    );

Table created.

SQL> insert into timeslot (id) values (1);

1 row created.

SQL>

我插入了什么?

SQL> select * From timeslot;

        ID TS
---------- --------
         1 03.06.20

SQL>

哦,天啊,那看起来很丑……不可能知道它到底是什么,因为它可能是

  • 2020 年 3 月 6 日或
  • 2003 年 6 月 20 日或
  • 1920 年 6 月 3 日或...

但是,那只是因为我数据库中的当前 NLS 设置显示 date 数据类型值。 Oracle 以 7 字节二进制格式存储日期(我们人类无法识别)因此我们必须做 something 来很好地呈现这些值。例如:

SQL> alter session set nls_date_format = 'dd.mm.yyyy';

Session altered.

SQL> select * From timeslot;

        ID TS
---------- ----------
         1 03.06.2020

好的,这是日期,但是-时间呢?

SQL> alter session set nls_date_format = 'dd.mm.yyyy hh24:mi:ss';

Session altered.

SQL> select * From timeslot;

        ID TS
---------- -------------------
         1 03.06.2020 19:38:37

SQL>

当然,你不会每次都alter session。您将使用具有适当格式掩码的 to_char 函数:

SQL> select id,
  2         to_char(ts, 'dd.mm.yyyy hh24:mi:ss') ts
  3  from timeslot;

        ID TS
---------- -------------------
         1 03.06.2020 19:38:37

SQL>

或者,如果您想 拆分 日期和时间组件,您

SQL> select id,
  2         to_char(ts, 'dd.mm.yyyy') c_date,
  3         to_char(ts, 'hh24:mi:ss') c_time
  4  from timeslot;

        ID C_DATE     C_TIME
---------- ---------- --------
         1 03.06.2020 19:38:37

SQL>

或者,创建一个为您执行此操作的 VIEW:

SQL> create or replace view v_timeslot as
  2  select id,
  3         to_char(ts, 'dd.mm.yyyy') c_date,
  4         to_char(ts, 'hh24:mi:ss') c_time
  5  from timeslot;

View created.

SQL> select * from v_timeslot;

        ID C_DATE     C_TIME
---------- ---------- --------
         1 03.06.2020 19:38:37

SQL>