hi,
Please check the below one.
DECLARE @Month nvarchar(2)
DECLARE @Year nvarchar(4)
Declare @MaxDay int
SET @Month = '7'
SET @Year = '2012'
Select @MaxDay=Day(DateAdd(d, -1, DateAdd(m, 1, @Year+ '-' + (@Month) + '-1 23:59:59.998')))
select Case when DAY(Duedate)<=@MaxDay Then Cast(DAY(Duedate) as varchar) +'-'+ Substring(DATENAME(m, '1900-' + CAST(@Month as varchar(2)) + '-1'),1,3) +'-'+@Year
else Cast(@MaxDay as varchar) + +'-'+Substring(DATENAME(m, '1900-' + CAST(@Month as varchar(2)) + '-1'),1,3) +'-'+@Year
end from datemagics
here my table name is datemagics and Duedate is my column. You can replace with your table and column name