================== CASE 1 ================== CREATE FUNCTION [dbo].[fnc_Month_EndDate] ( @TargetDate DateTime, @AddMonths int ) RETURNS datetime AS BEGIN DECLARE @EndDate AS DateTime IF @AddMonths is NULL BEGIN set @AddMonths = 1 END else BEGIN set @AddMonths = @AddMonths +1 END IF @TargetDate IS NOT NULL BEGIN set @TargetDate = DateAdd( m, @AddMonths, @TargetDate) END BEGIN SELECT @EndDate = ( SELECT CAST(CAST(YEAR(@TargetDate) AS varchar(4)) + '-' + CAST(MONTH(@TargetDate) AS varchar(2)) + '-1' AS datetime) - 1 ) END RETURN @EndDate END
================== CASE 2 ================== CREATE FUNCTION [dbo].[fnc_Month_EndDate] ( @TargetDate DateTime, @AddMonths int ) RETURNS datetime AS BEGIN DECLARE @EndDate AS DateTime IF @AddMonths is NULL BEGIN set @AddMonths = 1 END
else BEGIN
set @AddMonths = @AddMonths +1
END BEGIN
SELECT @EndDate = ( SELECT DATEADD(d, -1, DATEADD(m, @AddMonths, CAST(CAST(YEAR(@TargetDate) AS varchar(4)) + '-' + CAST(MONTH(@TargetDate) AS varchar(2)) + '-1' AS datetime))) ) END RETURN @EndDate END