How to convert datetime to timestamp in MS SQL stored function

半腔热情 提交于 2020-05-08 09:24:52

问题


There is a stored function which is called from table update trigger. Smt like this:

FUNCTION [dbo].[DateTime2ToBigInt](@dt DATETIME2(7))
RETURNS BIGINT

Need to convert input datetime to unix timestamp.

Tried CONVERT( timestamp, @dt) and CAST(@dt AS TIMESTAMP) but both result in

"Explicit conversion from data type datetime2 to timestamp is not allowed."

Of course it's possible to do by mathematics, but I can't believe, that mssql doesn't have direct convert function


回答1:


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 the function :

SELECT UNIX_TIMESTAMP(GETDATE());


来源:https://stackoverflow.com/questions/38915453/how-to-convert-datetime-to-timestamp-in-ms-sql-stored-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!