SYSDATE, NOW等“误区”-Oracle, PostgreSQL, MySQL

Oracle中最常用的时间类型:SYSDATE

Oracle内建了时间类型sysdate,以及时间函数current_date,current_timestamp,localtimestamp,systimestamp。其中sysdate使用最为频繁。

SQL> select dump(sysdate) from dual;

Typ=13 Len=8: 7,208,1,4,13,47,40,0

sysdate在Oracle内部以八个字节固定长度存储:

– Century, year
– Month, day
– Hour, minute, second
– Unused

SYSDATE完全依赖于操作系统时钟,因此数据库或者监听启动时操作系统的时区设置对它有直接影响。

MySQL中的SYSDATE(),NOW()

从表面意思看,容易混淆,误认为两者是相同的,和Oracle的sysdate也是类似,其实不然。先看看源代码,这里使用的是percona-server-5.7.24-27源码。

percona-server-5.7.24-27\sql\item_timefunc.h

class Item_func_now_local :public Item_func_now
{
protected:
  Time_zone *time_zone();
public:
  /**
     Stores the query start time in a field, truncating to the field's number
     of fractional second digits.
     

     @param field The field to store in.

   */
  static void store_in(Field *field);

  Item_func_now_local(uint8 dec_arg) :Item_func_now(dec_arg) {}
  Item_func_now_local(const POS &pos, uint8 dec_arg)
    :Item_func_now(pos, dec_arg)
  {}

  const char *func_name() const { return "now"; }
  virtual enum Functype functype() const { return NOW_FUNC; }
};

/*
  This is like NOW(), but always uses the real current time, not the
  query_start(). This matches the Oracle behavior.
*/
class Item_func_sysdate_local :public Item_datetime_func
{
public:
  Item_func_sysdate_local(uint8 dec_arg) :
    Item_datetime_func() { decimals= dec_arg; }
  bool const_item() const { return 0; }
  const char *func_name() const { return "sysdate"; }
  void fix_length_and_dec();
  bool get_date(MYSQL_TIME *res, my_time_flags_t fuzzy_date);
  /**
    This function is non-deterministic and hence depends on the 'RAND' pseudo-table.

    @retval Always RAND_TABLE_BIT

  */
  table_map get_initial_pseudo_tables() const { return RAND_TABLE_BIT; }
};

从代码可以看出NOW()返回的是查询开始的时间,SYSDATE()和Oracle的sysdate相类似。

PostgreSQL中的NOW()

postgresql-10.3\src\backend\utils\adt\timestamp.c

Datum
now(PG_FUNCTION_ARGS)
{
    PG_RETURN_TIMESTAMPTZ(GetCurrentTransactionStartTimestamp());
}

Datum
clock_timestamp(PG_FUNCTION_ARGS)
{
    PG_RETURN_TIMESTAMPTZ(GetCurrentTimestamp());
}

postgresql-10.3\src\backend\access\transam\xact.c

/*GetCurrentTransactionStartTimestamp
*/
TimestampTz
GetCurrentTransactionStartTimestamp(void)
{
return xactStartTimestamp;
}

代码中的逻辑很清晰, now()返回的是当前事务启动的时间。如果需要获取当前时间戳,可以改用clock_timestamp()。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容