
--select  [dbo].[GetPersianSeason](GETDATE())

CREATE FUNCTION [dbo].[GetPersianSeason]
(@GDate DATETime) RETURNS int
AS
BEGIN
	--DECLARE @GDate as datetime
	--SET @GDate=GETDATE()
	DECLARE @Season as int
	--Select DATEDIFF(MICROSECOND , @GDate,getDate())

    SELECT @Season=CASE 
                WHEN DATEDIFF(DAY,
                        CAST(
                            CASE 
                                WHEN @GDate >= CAST(CAST(YEAR(@GDate) AS VARCHAR(4)) + '-03-20' AS DATE)
                                    THEN CAST(YEAR(@GDate) AS VARCHAR(4)) + '-03-20'
                                ELSE CAST(YEAR(@GDate)-1 AS VARCHAR(4)) + '-03-20'
                            END
                        AS DATE),
                        @GDate
                    ) < 93 THEN 1
                WHEN DATEDIFF(DAY,
                        CAST(
                            CASE 
                                WHEN @GDate >= CAST(CAST(YEAR(@GDate) AS VARCHAR(4)) + '-03-20' AS DATE)
                                    THEN CAST(YEAR(@GDate) AS VARCHAR(4)) + '-03-20'
                                ELSE CAST(YEAR(@GDate)-1 AS VARCHAR(4)) + '-03-20'
                            END
                        AS DATE),
                        @GDate
                    ) < 186 THEN 2
                WHEN DATEDIFF(DAY,
                        CAST(
                            CASE 
                                WHEN @GDate >= CAST(CAST(YEAR(@GDate) AS VARCHAR(4)) + '-03-20' AS DATE)
                                    THEN CAST(YEAR(@GDate) AS VARCHAR(4)) + '-03-20'
                                ELSE CAST(YEAR(@GDate)-1 AS VARCHAR(4)) + '-03-20'
                            END
                        AS DATE),
                        @GDate
                    ) < 279 THEN 3
                ELSE 4
            END
	return @Season
END
GO