[英]How to get number of days in a month in SQL Server
如果我們輸入月份編號或月份名稱,甚至是日期,是否有辦法獲取SQL Server中一個月的天數?
如果您有約會,那么只需:
select day(eomonth(date))
如果您有月份編號,那么:
select day(eomonth(datefromparts(2020, month_number, 1)))
您可以使用:
select day(eomonth ('2018-02-01')) as NoOfDays
結果將是:
NoOfDays
-----------
28
如果您有日期並且在2012年或之后:
SELECT day(eomonth(yourdate))
處理二月時,月份名稱/號碼自動容易出錯 - 您認為它是28或29,您在進行計算時指的是哪一年等。
嘗試使用
SELECT day(eomonth(yourdate))
如果您使用的是sql-server 2008或更早版本:
日期作為輸入
DECLARE @date DATETIME = getdate()
SELECT day(dateadd(m, datediff(m, -1, @date), -1))
月份和年份作為輸入
DECLARE @year INT = 2018
DECLARE @month INT = 2
SELECT day(dateadd(m, @month + datediff(m, 0, cast(@year as char(4))), -1))
2012年之前,沒有eomonth()
如果你有約會
select day(dateadd(month, datediff(month, 0, @date) + 1, -1))
如果你有年和月
declare @year int = 2018,
@month int = 8
select dateadd(month, @month, dateadd(year, @year - 1900, -1))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.