﻿-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date, ,>
-- Description:	<Description, ,>
-- =============================================
--select [C6MartPeriodico].[getTrimestre_EMAIL_PB](getdate())
CREATE FUNCTION [C6MartPeriodico].[getTrimestre_EMAIL_PB] 
(
	@data datetime
)
RETURNS VARCHAR(8)
AS
BEGIN
	-- Declare the return variable here
	DECLARE @retData VARCHAR(8)
	SET @retData = CASE
		WHEN @data >= CAST(CAST(YEAR(@data) AS VARCHAR) + dbo.getParametro('TrimestreMarzo') AS DATETIME) -30 AND @data < CAST(CAST(YEAR(@data) AS VARCHAR) + dbo.getParametro('TrimestreGiugno') AS DATETIME) - 29 THEN CAST(YEAR(@data) AS VARCHAR) + dbo.getParametro('TrimestreMarzo')
		WHEN @data >= CAST(CAST(YEAR(@data) AS VARCHAR) + dbo.getParametro('TrimestreGiugno') AS DATETIME) - 29 AND @data < CAST(CAST(YEAR(@data) AS VARCHAR) + dbo.getParametro('TrimestreSettembre') AS DATETIME) - 29 THEN CAST(YEAR(@data) AS VARCHAR) + dbo.getParametro('TrimestreGiugno')
		WHEN @data >= CAST(CAST(YEAR(@data) AS VARCHAR) + dbo.getParametro('TrimestreSettembre') AS DATETIME) -29 AND @data < CAST(CAST(YEAR(@data) AS VARCHAR) + dbo.getParametro('TrimestreDicembre') AS DATETIME) - 30 THEN CAST(YEAR(@data) AS VARCHAR) + dbo.getParametro('TrimestreSettembre')
		WHEN @data >= CAST(YEAR(@data) AS VARCHAR)+'0101' AND @data < CAST(CAST(YEAR(@data) AS VARCHAR) + dbo.getParametro('TrimestreMarzo') AS DATETIME)-30 THEN CAST(YEAR(@data) - 1 AS VARCHAR) + dbo.getParametro('TrimestreDicembre')
		WHEN @data >= CAST(CAST(YEAR(@data) AS VARCHAR) + dbo.getParametro('TrimestreDicembre') AS DATETIME) -31 AND @data <= CAST(CAST(YEAR(@data) AS VARCHAR) + dbo.getParametro('TrimestreDicembre') AS DATETIME) +1 THEN CAST(YEAR(@data) AS VARCHAR) + dbo.getParametro('TrimestreDicembre')
	END
RETURN @retData
END