
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--Usage: ([dbo].[FARSI_DATE2]([Date]))
		
CREATE FUNCTION [dbo].[FARSI_DATE_MON] 
(@DATE DATETIME) RETURNS INT
AS
BEGIN
	DECLARE @RYEAR  int 
	DECLARE @RMONTH int 
	DECLARE @RDAY   int 
	DECLARE @FARSIDate char(25)
	DECLARE @FARSIMONTH CHAR(2)
	DECLARE @FARSIDAY CHAR(2)

    SET @RYEAR  = DATEPART(yyyy, @DATE)
    --SET @RYEAR  = DATEPART(yyyy, @DATE)-@RYEAR*100
	SET @RMONTH = DATEPART(mm,@DATE)
	SET @RDAY   = DATEPART(dd, @DATE)

--	SET @FARSIDATE=+dbo.MyStr(@RDAY,2)+'/'+dbo.MyStr(@RMONTH,2)+'/'+dbo.MyStr(@RYEAR,4)
--	RETURN(@FARSIDATE)

	--DECLARE @SAL    int
	DECLARE @MAH    int
	--DECLARE @ROZ    int

	DECLARE @a  Int
	DECLARE @c  Int
	DECLARE @Y  Int
	DECLARE @i  Int
	DECLARE @j  Int
	DECLARE @TEMP  INT
	
	SET @A=79
	
	SET @Y = @RYear
	
	IF (@Y < 1964) Or (@Y > 2028)
	BEGIN
		RETURN(0)
	END
	ELSE
	BEGIN
		IF @Y > 1963 And @Y < 1996 
		BEGIN
		    IF (@Y % 4) = 0 
		    BEGIN
		        SET @a = @a + 1
		        SET @c = dbo.CheckTableFarsi_Date(2,@RMonth - 1) + @RDay
		    END
		    Else
		    BEGIN
		        SET @c = dbo.CheckTableFarsi_Date(1,@RMonth - 1) + @RDay
		    END
		END
		Else
		BEGIN
			If (@Y % 4) = 0
			BEGIN
		        SET @c = dbo.CheckTableFarsi_Date(3,@RMonth - 1) + @RDay
			END
			Else
			BEGIN
				If (@Y % 4) = 1 
				BEGIN
			        SET @a = @a + 1
			        SET @c = dbo.CheckTableFarsi_Date(4,@RMonth - 1) + @RDay
				END
				Else
				BEGIN
			        SET @c = dbo.CheckTableFarsi_Date(1,@RMonth - 1) + @RDay
				END
			END
		End
		
		If @c > @a 
		BEGIN
		    SET @i = 9
		    SET @c = @c - @a
		    --SET @sal = @Y - 621
		    While dbo.CheckTableFarsi_Date(5,@I) > @c And @i > 0
			BEGIN
		        SET @i = @i - 1
		    END
		    If dbo.CheckTableFarsi_Date(5,@I) = @c And @i > 0 
			BEGIN
				SET @i = @i - 1
			END
		    --SET @roz = @c - dbo.CheckTableFarsi_Date(5,@I)
		    SET @mah = @i + 1
		END
		Else
		BEGIN
		    SET @j = 2
		    SET @c = @c + 10
		    --SET @sal = @Y - 622
		    While dbo.CheckTableFarsi_Date(6,@J) > @c And @j > 0
			BEGIN
		        SET @j = @j - 1
		    END
		    If dbo.CheckTableFarsi_Date(6,@J) = @c And @j > 0 
			BEGIN
				SET @j = @j - 1
			END
		    --SET @roz = @c - dbo.CheckTableFarsi_Date(6,@J)
		    SET @mah = @j + 10
		END
	END

	return @MAH
END


GO


