2013-04-01 188 views
0

如果我有本月的名字,那麼我怎麼能在SQL中的那個月的第一天和最後一天?查詢當月的第一天和最後一天

我有這樣的查詢返回月份名稱:

DECLARE @StartDate DATETIME, 
     @EndDate DATETIME; 

SELECT @StartDate = '20110501'   
     ,@EndDate = '20110801'; 


SELECT DATENAME(MONTH, DATEADD(MONTH, x.number, @StartDate)) AS MonthName 
FROM master.dbo.spt_values x 
WHERE x.type = 'P'   
AND  x.number <= DATEDIFF(MONTH, @StartDate, @EndDate) 

結果:

results

現在,我怎樣才能得到的那幾個月的第一天和最後一天?改變查詢。

回答

3

試試這個: -

DECLARE @StartDate DATETIME, 
     @EndDate DATETIME; 

SELECT @StartDate = '20110501'   
     ,@EndDate = '20110801'; 


SELECT DATENAME(MONTH, DATEADD(MONTH, x.number, @StartDate)) AS MonthName, 
CONVERT(VARCHAR(25), 
DATEADD(dd,-(DAY(DATEADD(MONTH, x.number, @StartDate))-1),DATEADD(MONTH, x.number, @StartDate)),101) as FirstDay, 
CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(DATEADD(mm,1,DATEADD(MONTH, x.number, @StartDate)))),DATEADD(mm,1,DATEADD(MONTH, x.number, @StartDate))),101) as LastDay 
FROM master..spt_values x 
WHERE x.type = 'P'   
AND  x.number <= DATEDIFF(MONTH, @StartDate, @EndDate) 

結果: -

MonthName  FirstDay   LastDay 
    May   05/01/2011  05/31/2011  
June   06/01/2011  06/30/2011  
July   07/01/2011  07/31/2011  
August   08/01/2011  08/31/2011  

結果得到採取的幫助下從this查詢

+0

完善!謝謝... – PookPook

1

此代碼爲您提供了當月第一次約會:

DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0) 

如果你知道本月然後數

SELECT  DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) + @MonthNumber, 0) 

也是一樣月的結束日期

SELECT DATEADD(MILLISECOND, -1, 
     DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) - @@MonthNumber+ 1, 0)) 
2

如果你想要一個更普遍和簡單的解決方案:

DECLARE @startdate AS DATETIME = GETDATE() 
SELECT  
DATEADD(MONTH, DATEDIFF(MONTH, 0, @startdate) , 0) as startMonth, 
DATEADD(SECOND, -1, DATEADD(MONTH, 1, DATEADD(MONTH, DATEDIFF(MONTH, 0, @startdate) , 0))) as endMonth 

給出結果:

startMonth    endMonth 
----------------------- ----------------------- 
2013-06-01 00:00:00.000 2013-06-30 23:59:59.000 
+0

非常簡單...謝謝 – PookPook

相關問題