How to get the number of days in the month?

xiaoxiao2021-03-06  66

--method one

Declare @MONTH INT, @Year Int

SELECT @Month = 6, @Year = 2004

Select Datepart (DD, DateAdd (M, 1, Cast (Str (@Month) '/ 01 /' STR (@Year) AS

DateTime)) - 1)

--Method Two

Declare @date datetime

Set @date = getdate ()

SELECT CAST

- First Day of Next Month

Dateadd (Month, Datediff (Month, 0, @ Date) 1,0)

-

- First Day of current Month

Datead (Month, Datediff (Month, 0, @ Date), 0)

As int)

- Method three

You can also write a UDF to implement:

Create function fn_numofdaysinmon (@date datetime)

Returns Int

AS

Begin

Declare @begmonth datetime, @ endmonth datetime, @ days int

Select @ begmonth = dateadd (Month, Datediff (Month, 0, @ Date), 0)

Select @ endmonth = dateadd (DD, -Datepart (DD, @ Date), DateAdd (mm, 1, @ Date))

Select @ days = datediff (DD, @ Begmonth, @ endmonth) 1

Return @days

end

转载请注明原文地址:https://www.9cbs.com/read-119757.html

New Post(0)