gpt4 book ai didi

sql - 如何将此 T-SQL 代码转换为 PostgreSQL/plpgsql

转载 作者:行者123 更新时间:2023-11-29 14:05:34 24 4
gpt4 key购买 nike

我需要将以下 tsql 函数代码转换为 plpgsql 函数,但我完全不知道如何操作:

BEGIN
DECLARE @StartDate DATETIME
DECLARE @ResultDate DATETIME

SET @StartDate = CONVERT(DATETIME, 0)

SET @ResultDate =
CASE @Type
WHEN 0 THEN DATEADD(mi, FLOOR(DATEDIFF(mi, @StartDate, @Date) / CAST(@Interval AS FLOAT)) * @Interval, @StartDate)
WHEN 1 THEN DATEADD(mi, CEILING(DATEDIFF(mi, @StartDate, @Date) / CAST(@Interval AS FLOAT)) * @Interval, @StartDate)
ELSE @Date
END

RETURN @ResultDate

这里是全文:

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO

ALTER FUNCTION [dbo].[GetIntervalDate]

(
@Date DATETIME,
@Type INT,
@Interval INT
)
RETURNS DATETIME

AS

BEGIN

DECLARE @StartDate DATETIME

DECLARE @ResultDate DATETIME

SET @StartDate = CONVERT(DATETIME, 0)

SET @ResultDate =
CASE @Type
WHEN 0 THEN DATEADD(mi, FLOOR(DATEDIFF(mi, @StartDate, @Date) / CAST(@Interval AS FLOAT)) * @Interval, @StartDate)
WHEN 1 THEN DATEADD(mi, CEILING(DATEDIFF(mi, @StartDate, @Date) / CAST(@Interval AS FLOAT)) * @Interval, @StartDate)
ELSE @Date
END

RETURN @ResultDate
END

最佳答案

明白了:

CREATE FUNCTION get_interval_date("@Date" timestamp, "@Type" int, "@Interval" int)
RETURNS timestamp with time zone AS
$BODY$
DECLARE
_mystamp timestamp;
_round_secs decimal;
BEGIN
_round_secs := "@Interval"::decimal;

IF "@Type" = 0 THEN
RETURN timestamptz 'epoch'
+ FLOOR((EXTRACT(EPOCH FROM "@Date"))::int / _round_secs) * _round_secs * INTERVAL '1 second';
ELSIF "@Type" = 1 THEN
RETURN timestamptz 'epoch'
+ CEIL((EXTRACT(EPOCH FROM "@Date"))::int / _round_secs) * _round_secs * INTERVAL '1 second';
ELSE
RETURN "@Date";
END IF;
END;
$BODY$ LANGUAGE 'plpgsql' IMMUTABLE;

也许其他人需要这样的东西。

关于sql - 如何将此 T-SQL 代码转换为 PostgreSQL/plpgsql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3361660/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com