获取动态上个月结束日期并插入

时间:2018-03-06 16:14:49

标签: sql-server sql-server-2008 tsql

我正在尝试动态获取上个月的最后一天并将其传递给查询。我尝试了以下想法,但它没有用。

DECLARE @PrevMonthLastDay DATE=(SELECT CONVERT(CHAR(15),DATEADD(DD,-Day(GETDATE()),GETDATE()),106))
--PRINT @PrevMonthLastDay
INSERT INTO [TBL_ParseRawDataHist]  
SELECT   [SrcID],[ASOFDATE],
         dbo.SplitIndex('|', LTRIM(RTRIM([SrcID])), 1) AS Parse1, 
         dbo.SplitIndex('|', LTRIM(RTRIM([SrcID])), 2) AS Parse2,
         dbo.SplitIndex('|', LTRIM(RTRIM([SrcID])), 3) AS Parse3, 
         dbo.SplitIndex('|', LTRIM(RTRIM([SrcID])), 4) AS Parse4, 
         dbo.SplitIndex('|', LTRIM(RTRIM([SrcID])), 5) AS Parse5, 
         dbo.SplitIndex('|', LTRIM(RTRIM([SrcID])), 6) AS Parse6, 
         dbo.SplitIndex('|', LTRIM(RTRIM([SrcID])), 7) AS Parse7, 
         dbo.SplitIndex('|', LTRIM(RTRIM([SrcID])), 8) AS Parse8,
         dbo.SplitIndex('|', LTRIM(RTRIM([SrcID])), 9) AS Parse9, 
         dbo.SplitIndex('|', LTRIM(RTRIM([SrcID])), 10) AS Parse10          
FROM     TBL_FR2052A_RAW_DATA_HIST  
--WHERE  ASOFDATE = '02/28/2018'
WHERE    ASOFDATE = ''' + CAST(@PrevMonthLastDay AS varchar(15)) + '''

结果:从字符串转换日期和/或时间时转换失败。

我在这里做错了什么?我正在使用SQL Server 2008!

4 个答案:

答案 0 :(得分:1)

您无需转换为字符串,只需使用sudo ln -s /bin/bison /bin/yacc dateadd

day

结果:

DECLARE @CurrentDate as date = GETDATE()

SELECT  @CurrentDate As CurrentDate, 
        DATEADD(DAY, -DAY(@CurrentDate), @CurrentDate) As EndOfLastMonth

2012版本引入了EOMONTH()内置函数,因此如果您升级SQL Server,可以执行此操作以获得相同的结果:CurrentDate EndOfLastMonth 06.03.2018 28.02.2018

<强>更新
这是完整的插入语句:

select eomonth(dateadd(month,-1,getdate()))

答案 1 :(得分:1)

每月的第一天和最后一天:

DECLARE @PrevMonthFirstDay DATE= DATEADD(month, DATEDIFF(month, 0, getdate()), 0)

DECLARE @PrevMonthLastDay DATE= DATEADD(dd, -1, DATEADD(mm, DATEDIFF(mm, 0, GETDATE()) + 1, 0))

答案 2 :(得分:1)

您无法将字符串与DATE连接起来,您必须将其作为字符串进行CAST处理:

WHERE    ASOFDATE = ''' + CAST(@PrevMonthLastDay AS varchar(15)) + ''''

答案 3 :(得分:0)

Zohar,你的更新代码给了我一个尝试的想法。最终,这对我有用。

DECLARE @PrevMonthLastDay DATE=(SELECT CONVERT(CHAR(15),DATEADD(DD,-Day(GETDATE()),GETDATE()),106))
Print @PrevMonthLastDay

INSERT   INTO [TBL_ParseRawDataHist]  
SELECT   [SrcID],[ASOFDATE],
         dbo.SplitIndex('|', LTRIM(RTRIM([SrcID])), 1) AS Parse1, 
         dbo.SplitIndex('|', LTRIM(RTRIM([SrcID])), 2) AS Parse2,
         dbo.SplitIndex('|', LTRIM(RTRIM([SrcID])), 3) AS Parse3, 
         dbo.SplitIndex('|', LTRIM(RTRIM([SrcID])), 4) AS Parse4, 
         dbo.SplitIndex('|', LTRIM(RTRIM([SrcID])), 5) AS Parse5, 
         dbo.SplitIndex('|', LTRIM(RTRIM([SrcID])), 6) AS Parse6, 
         dbo.SplitIndex('|', LTRIM(RTRIM([SrcID])), 7) AS Parse7, 
         dbo.SplitIndex('|', LTRIM(RTRIM([SrcID])), 8) AS Parse8,
         dbo.SplitIndex('|', LTRIM(RTRIM([SrcID])), 9) AS Parse9, 
         dbo.SplitIndex('|', LTRIM(RTRIM([SrcID])), 10) AS Parse10          
FROM     TBL_FR2052A_RAW_DATA_HIST  
WHERE    ASOFDATE = @PrevMonthLastDay 

谢谢!