--方法一
DECLARE @month int, @year int
SELECT @month = 11, @year = 2008
SELECT DATEPART(dd,DATEADD(m,1,CAST(STR(@month) + '/01/' + STR(@year) as datetime)) - 1)
--执行过程分析
SELECT STR(@month) + '/01/' + STR(@year) as datetime--整型转化成字符串型
SELECT CAST(STR(@month) + '/01/' + STR(@year) as datetime)--字符串转化成日期型
SELECT DATEADD(m,1,CAST(STR(@month) + '/01/' + STR(@year) as datetime))--月份加1
SELECT DATEPART(dd,DATEADD(m,1,CAST(STR(@month) + '/01/' + STR(@year) as datetime)) - 1)--最后天数再减1
--方法二
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
DATEADD(MONTH,DATEDIFF(MONTH,0,@DATE),0)
AS INT )
--方法三
这个你也可以写一个UDF来实现:
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
--sql server中调用函数的方法
select dbo.fn_NumOfDaysInMon (getdate())