oracle sysdate mysql_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()。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值