简体   繁体   English

将vba日期函数转换为sql

[英]convert vba date function to sql

I need help converting the following vba code to a similar SQL string.我需要帮助将以下 vba 代码转换为类似的 SQL 字符串。

    vDt = Now()
    vStartDate = UCase(Format(DateSerial(Year(vDt), Month(vDt) - 1, 1), "DD-MMM-YYYY"))
    vEndDate = UCase(Format(DateSerial(Year(vDt), Month(vDt), 0), "DD-MMM-YYYY"))

If I'm understanding this correctly, you want the start date to be the first day of the previous month and the end date to be the last day of the current month.如果我理解正确,您希望开始日期是上个月的第一天,结束日期是当月的最后一天。 Then you want to convert them to the date format DD-MMM-YYYY.然后您想将它们转换为日期格式 DD-MMM-YYYY。 If so, below would be the corresponding SQL:如果是这样,下面将是相应的 SQL:

DECLARE @now DATETIME;
DECLARE @start DATETIME;
DECLARE @end DATETIME;
SET @now = GETDATE();
SET @start = DATEADD(MONTH, -1, DATEADD(MONTH, DATEDIFF(MONTH, 0, @now), 0));
SET @end = EOMONTH(@now);

SELECT UPPER(REPLACE(CONVERT(VARCHAR(12), @start, 106), ' ', '-')) AS StartDate,
    UPPER(REPLACE(CONVERT(VARCHAR(12), @end, 106), ' ', '-')) AS EndDate;

EDIT - Sorry I should mention that this is in Microsoft T-SQL and not Teradata SQL Assistant (thank you @a_horse_with_no_name).编辑 - 抱歉,我应该提到这是在 Microsoft T-SQL 而不是 Teradata SQL Assistant(谢谢@a_horse_with_no_name)。 I'm not familiar with Teradata so I can't give you the exact answer, however I believe you can find similar functions to translate the above answer.我对 Teradata 不熟悉,所以我不能给你确切的答案,但是我相信你可以找到类似的函数来翻译上述答案。

In Teradata SQL you get the 1st day of the previous month using在 Teradata SQL 中,您使用

 Trunc(Add_Months(Current_Date, -1), 'mon')

and the last day of the current month:以及当月的最后一天:

Last_Day(Current_Date)

Of course this returns a data, if you want a DD-MMM-YYYY string:当然这会返回一个数据,如果你想要一个DD-MMM-YYYY字符串:

SELECT
   To_Char(Trunc(Add_Months(Current_Date, -1), 'MON'), 'DD-MON-YYYY')
  ,To_Char(Last_Day(Current_Date), 'DD-MON-YYYY')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM