CREATE FUNCTION [dbo].[Club_GetByMobile](@Code VARCHAR(12), @FactorId BIGINT, @JoinNu BIGINT)
RETURNS @ClubCache  TABLE
(
   Name NVARCHAR(60),
   Addr NVARCHAR(150),
   lastMessage NVARCHAR(120),
   Mobile VARCHAR(11),
   BirthDate VARCHAR(10),
   IsMale TINYINT, 
   IsOpenPanel Bit
)
BEGIN 
    DELETE FROM @ClubCache
	DECLARE @Mobile CHAR(12) = @Code
	DECLARE @RestOfCodes VARCHAR(MAX) = SUBSTRING(@Mobile,2,11)
	DECLARE @TmpMobile CHAR(11) 
	DECLARE @TmpId BIGINT
	DECLARE @IsOpenPanel Bit
	IF LEN(@RestOfCodes) = 11
	BEGIN
		IF ISNUMERIC(@RestOfCodes) = 1
		BEGIN 
			Select @TmpMobile = Mobile FROM dbo.Tbl_ClubH WHERE Mobile = @RestOfCodes
			IF (ISNULL(@TmpMobile,'') = '') OR (ISNULL(@TmpMobile,Null) = Null)
			BEGIN
			  SET @Mobile = @RestOfCodes
   			  INSERT INTO @ClubCache(Name,Addr,lastMessage,Mobile,BirthDate,IsMale, IsOpenPanel)
			  SELECT '' Name,'' Addr,'' lastMessage,@Mobile, '' BirthDate ,1 IsMale, 0  
			END 
			ELSE
			BEGIN 
              SET @Mobile = @TmpMobile
   			  INSERT INTO @ClubCache(Name,Addr,lastMessage,Mobile,BirthDate,IsMale, IsOpenPanel)
              SELECT  Name, Addr, lastMessage,@Mobile,  Dbo.MiladiToShamsi(BirthDate) BirthDate  , IsMale,0  FROM dbo.Tbl_ClubH WHERE Mobile = @Mobile  
            END 
		END 
	END
	ELSE
    BEGIN
	  IF @JoinNu = 0
	  BEGIN 
	    SET @TmpId = (SELECT Clubid FROM TmpHeadh WHERE Id_Havaleh = @Factorid) 
		SET @IsOpenPanel = 1
	  END 
	  ELSE
	  BEGIN 
        SET @TmpId = @JoinNu         
		SET @IsOpenPanel = 0
	  END 
   	  INSERT INTO @ClubCache(Name,Addr,lastMessage,Mobile,BirthDate,IsMale,IsOpenPanel)
      SELECT  Name, Addr, lastMessage,Mobile,  Dbo.MiladiToShamsi(BirthDate) BirthDate  , IsMale, @IsOpenPanel  FROM dbo.Tbl_ClubH WHERE Autoid = @TmpId
    END 
RETURN
END 




