Code Example 1:

create function DaysInMonth (@when datetime)
returns int
as
BEGIN
declare	@rv int

if datepart(month, @when) = 2
begin
    if datepart(year, @when) % 400 = 0
    select @rv = 29
else
    if datepart(year, @when) % 100 = 0
    select @rv = 28
else
    if datepart(year, @when) % 4 = 0
    select @rv = 29
else
    select @rv = 28
end -- if
else
begin
select @rv = case (datepart(month, @when))
    when 4 then 30
    when 6 then 30
    when 9 then 30
    when 11 then 30
    else 31
    end -- case
end -- else
  
return @rv

END -- fn def