CREATE PROCEDURE ClubMemberShipDrug @IdHavaleh BIGINT, @Id INT OUTPUT 
AS  
DECLARE @Mobile VARCHAR(11)
DECLARE @ISClubMember BIT
DECLARE @ClubId INT 

DECLARE @ClubInfo AS TABLE
(
  Family nvarchar(60),
  Mobile VARCHAR(11),
  Addr nvarchar(150),
  IsMale BIT,
  BirthDate SMALLDATETIME,
  ISClubMember BIT,
  ClubId INT 
)
INSERT INTO @ClubInfo
(
    Family,
    Mobile,
    Addr,
    IsMale,
    BirthDate,
	ISClubMember,
	ClubId
)
SELECT Resive_Name, dbo.Notebimeh.Mobile, Mess, TypeSex, Notebimeh.BirthDate 
, CASE
    WHEN ISNULL(dbo.Tbl_ClubH.Mobile,'0') <> '0' THEN 1
	ELSE 0
  END, dbo.Tbl_ClubH.AutoId
FROM dbo.TmpDrugH
INNER JOIN dbo.Notebimeh ON Notebimeh.Note_Code = TmpDrugH.Note_Code
AND Notebimeh.Sazman_Code = TmpDrugH.Sazman_Code
LEFT JOIN dbo.Tbl_ClubH ON Tbl_ClubH.Mobile = Notebimeh.Mobile
WHERE Id_Havaleh = @IdHavaleh AND ISNULL(Notebimeh.Mobile,'0') <> '0'

SELECT @ClubId = ClubId, @IsClubMember = IsClubMember FROM @ClubInfo WHERE ISClubMember = 1
IF ISNULL(@IsClubMember,0)  = 1
BEGIN 
  UPDATE Tbl_ClubH SET Name = Family, Addr = [@ClubInfo].Addr, BirthDate = [@ClubInfo].BirthDate FROM dbo.Tbl_ClubH
  INNER JOIN @ClubInfo ON [@ClubInfo].Mobile = Tbl_ClubH.Mobile
END 
ELSE
BEGIN 
  INSERT INTO dbo.Tbl_ClubH(Mobile,Name,Addr,Tarikh,IsMale, BirthDate)
  SELECT Mobile, Family, Addr, GETDATE(),IsMale, BirthDate FROM @ClubInfo 
  SELECT @ClubId = SCOPE_IDENTITY()
END 
SET @Id = @ClubId
RETURN @Id
