In Microsoft SQL Server 2012 or above, is it possible to convert a datetime value to Unix time stamp in a single select statement? If so, how can it be done?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Converting a datetime to unix timestamp is easy, but involves error prone typing the following:
@timestamp=DATEDIFF(second,{d '1970-01-01'},@datetime)
Where @datetime is the datetime value you want to convert. The {d ‘yyyy-mm-dd’} notation is an ODBC escape sequence.
The function:
CREATE FUNCTION UNIX_TIMESTAMP (
@ctimestamp datetime
)
RETURNS integer
AS
BEGIN
/* Function body */
declare @return integer
SELECT @return = DATEDIFF(SECOND,{d '1970-01-01'}, @ctimestamp)
return @return
END
Try it out now like below @Ousman :
SELECT UNIX_TIMESTAMP(GETDATE());