-- Calculate the number of Sundays in a month of a year (excluding Saturday) Create Function f_getnums (@ year_month varchar (8) returns INTAS begin declare @ BDT datetime, @ EDT datetime, @ I int set @ I = 0 set @ BDT = cast (@ year_month + '-01' As datetime) set @ EDT = dateadd (D,-1, dateadd (month, 1, cast (@ year_month + '-01' as datetime) while datediff (D, @ BDT, @ EDT)> = 0 begin if -- datepart (DW, @ BDT) = 1 or datepart (DW, @ BDT) = 7 begin set @ I = @ I + 1 end set @ BDT = dateadd (d, 1, @ BDT) end return @ I enddeclare @ date datetime set @ date = '2017-12-01 '-- 1. select datediff (DD, @ date, dateadd (mm, 1, @ date) -- 2. obtain the number of Sunday select DBO instances in a month in a year. f_getnums (convert (varchar (07), @ date, 120) as workday -- 3. obtain the number of working days of a month in a year (excluding Sunday only) Select datediff (DD, @ date, dateadd (mm, 1, @ date)-DBO. f_getnums (convert (varchar (07), @ date, 120) as workday