Questions[SQL]:Calculate the Number of Days in a Month

Q:Can you use a batch SQL or store procedure to calculating the Number of Days in a Month?

A:

解法一:使用CTE,结构清晰

     with  arg0  as
    (
        
-- 计算当月第一天
         select   cast (
            
cast ( year ( getdate ())  as   varchar ) + ' - ' + cast ( month ( getdate ())  as   varchar ) + ' -01 '  
            
as   datetime as  nowdt
    ),
    arg1 
as
    (
        
-- 计算下月第一天
         select   dateadd (mm, 1 ,nowdt)  as  dt  from  arg0
    ),
    arg2 
as
    (
        
-- 计算下月减1,即本月最后一天
         select   dateadd (dd, - 1 , dt)  as  dt  from  arg1
    ),
    arg3 
as
    (
        
-- 取天数部分
         select   datepart (dd, dt)  as  daies  from  arg2
    )
    
select   *   from  arg3

 

解法二:使用变量

declare   @now    datetime
set   @now =   cast (
            
cast ( year ( getdate ())  as   varchar ) + ' - ' + cast ( month ( getdate ())  as   varchar ) + ' -01 '  
            
as   datetime
declare   @day   int
set   @day   =   datepart (dd,  dateadd (dd, - 1 dateadd (mm, 1 , @now )))
select   @day


解法三:单一语句

select   datepart (dd, dateadd (dd, - 1 , dateadd (mm, 1 , cast ( cast ( year ( getdate ())  as   varchar ) + ' - ' + cast ( month ( getdate ())  as   varchar ) + ' -01 '   as   datetime ))));

你可能感兴趣的:(number)