CREATE FUNCTION [dbo].[ShamsiToMiladi](@FD NCHAR(10))
RETURNS SMALLDATETIME AS  
BEGIN
    DECLARE @syy BIGINT 
    DECLARE @smm BIGINT 
    DECLARE @sdd BIGINT 
    DECLARE @val  BIGINT 
    DECLARE @By BIGINT 
    DECLARE  @mstart DATETIME 
    DECLARE @Mc  INT

    DECLARE @sbase INT
    DECLARE @sleapbmp NCHAR(150)
    DECLARE @ind AS INT

    
    
--    set @fd='1384/02/11'
    SET @mstart = '1900/03/21'

    SET @syy = SUBSTRING(@FD,1,4)
    SET @smm = SUBSTRING(@FD,6,2)
    SET @sdd = SUBSTRING(@FD,9,2)
    SET @By = '1279'

    SET @sleapbmp='00001000100010001000100010001000010001000100010001000100010001000010001000100010001000100010001000010001000100010001000100010001'
    SET @sbase=475

--    print @smm

       SET   @val = 0

       WHILE (@By < @syy)
                 BEGIN
    
    SET @ind = (@By - @sbase) % (128 + 1)
        IF   SUBSTRING(@sleapbmp, @ind, 1)  ='1'
              BEGIN    
                     SET @val = @val + 1
                         END        

              SET @val = @val + 365
              SET @By = @By + 1
      END

      SET @Mc=1
      WHILE  @mc< @smm
            
          BEGIN 
            SELECT @val =CASE 
            WHEN @Mc= 1 THEN @Val+31 
            WHEN @Mc= 2 THEN @Val+31 
            WHEN @Mc= 3 THEN @Val+31 
            WHEN @Mc= 4 THEN @Val+31 
            WHEN @Mc= 5 THEN @Val+31 
            WHEN @Mc= 6 THEN @Val+31 
            WHEN @Mc= 7 THEN @Val+30
            WHEN @Mc= 8 THEN @Val+30 
            WHEN @Mc= 9 THEN @Val+30 
            WHEN @Mc= 10 THEN @Val+30 
            WHEN @Mc= 11 THEN @Val+30 
            WHEN @Mc= 12 THEN @Val+29
        END
                SET @mc=@mc+1    
    END
        SET @val = @val + @sdd
           RETURN   DATEADD(DAY,@val,@mstart ) 
END
