﻿
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date, ,>
-- Description:	<Description, ,>
-- =============================================
CREATE FUNCTION [dbo].[date_nextFirst]
(
	@date date
	,@unit varchar(1)
)
RETURNS date
AS
BEGIN
	DECLARE @ret date;
	SET @unit = LOWER(ISNULL(@unit, ''));

	SET @ret = CASE 
				WHEN @unit = 'y' THEN DATEADD(YEAR, 1, DATEFROMPARTS(YEAR(@date), 1,1))
				WHEN @unit = 'q' THEN DATEADD(MONTH, 4 - Month(@date) % 3, DATEFROMPARTS(YEAR(@date),MONTH(@date),1))
				WHEN @unit = 'm' THEN DATEADD(MONTH, 1, DATEFROMPARTS(YEAR(@date), MONTH(@date),1))
				WHEN @unit = 'w' THEN DATEADD(WEEK, 1, [dbo].[date_weekfirst](@date))
				WHEN @unit = 'd' THEN DATEADD(DAY, 1, @date)
				ELSE NULL
				END;

	RETURN @ret

END