CREATE PROCEDURE Club_Charge @Mobile CHAR(11) , @TmpId Numeric(18,0), @lastId Numeric(18,0) 
AS
DECLARE @Result MONEY
IF @TmpId = 0 
BEGIN
  SELECT @Result = SUM(ChargePrice) FROM dbo.Tbl_ScoreClub
  INNER JOIN dbo.ClubDetailScore ON ScoreId = Autoid
  INNER JOIN dbo.Tbl_ClubH ON Tbl_ClubH.AutoId = Tbl_ScoreClub.Id_Club
  WHERE Mobile = @Mobile AND PriceUse IS NULL
  AND CAST(GETDATE() AS DATE) BETWEEN CAST(StartDate AS DATE) AND CAST(EndDate AS DATE)

END
ELSE
BEGIN
  DECLARE @CachePrice MONEY = ISNULL((SELECT SUM(Price) FROM dbo.Tmp_Over_Under_Factor WITH (NOLOCK) WHERE ShowPrice = 3 AND Id_Havaleh = @TmpId),0) 
  IF @CachePrice > 0 
  BEGIN 
	  DECLARE @Id INT
	  DECLARE @ChargeValue MONEY 
	  DECLARE @ChargePrice MONEY
	  DECLARE CursorClubCharge CURSOR FOR 
	  SELECT ClubDetailScore.Id, ChargePrice FROM dbo.Tbl_ScoreClub
	  INNER JOIN dbo.ClubDetailScore ON ScoreId = Autoid
	  INNER JOIN dbo.Tbl_ClubH ON Tbl_ClubH.AutoId = Tbl_ScoreClub.Id_Club
	  WHERE Mobile = @Mobile AND PriceUse IS NULL
	  AND CAST(GETDATE() AS DATE) BETWEEN CAST(StartDate AS DATE) AND CAST(EndDate AS DATE)
	  ORDER BY Id
	  OPEN CursorClubCharge
	  FETCH NEXT FROM CursorClubCharge INTO @Id,@ChargePrice 
	  WHILE @@FETCH_STATUS = 0 
	  BEGIN
		SET @ChargeValue = @ChargePrice
		IF @CachePrice > @ChargePrice 
		  SET @CachePrice = @CachePrice - @ChargePrice 
		ELSE 
		  SET @ChargeValue = @CachePrice
		UPDATE dbo.ClubDetailScore SET PriceUse = @ChargeValue , DateUse = GETDATE(), FactorId = @lastId
		WHERE Id = @Id
      
		FETCH NEXT FROM CursorClubCharge INTO @Id,@ChargePrice 
	  END
	  CLOSE CursorClubCharge
	  DEALLOCATE CursorClubCharge
  END
  SET @Result = 24434
END 
SELECT @Result Result



