ALTER PROCEDURE WZ_DISCONNECT_MEMB
@memb___id varchar(10)
 AS
Begin	
set nocount on
	Declare @find_id varchar(10)
	Declare @ConnectStat tinyint
	Declare @day_chenh int
	Declare @timenow smalldatetime
	DECLARE @connecttime smalldatetime
	DECLARE @TimeOnlineDay int
	DECLARE @TimeOnlineYesterday int
	Declare @ServerName varchar(50)
	
	SET @day_chenh = 0			-- So ngay chenh giua thoi gian may tinh voi thoi gian thuc
	SET @timenow = DATEADD(d,@day_chenh,getdate())
	
	Set @ConnectStat = 0		--    1 = Connect , 0 = Disconnect
	Set @find_id = 'NOT'
	select @find_id = S.memb___id from MEMB_STAT S INNER JOIN MEMB_INFO I ON S.memb___id collate DATABASE_DEFAULT = I.memb___id collate DATABASE_DEFAULT
	       where I.memb___id = @memb___id

	if( @find_id <> 'NOT' )	--        
	begin		
		update MEMB_STAT set ConnectStat = @ConnectStat, DisConnectTM = @timenow
		 where memb___id = @memb___id
		
		-- Online time
		SELECT @connecttime=ConnectTM, @ServerName=ServerName FROM MEMB_STAT WHERE memb___id=@memb___id
		IF DATEDIFF(day, @connecttime, @timenow) > 1
			BEGIN
				SET @TimeOnlineDay = DATEDIFF(minute, DATEADD(day, DATEDIFF(day, 0, @timenow), 0), @timenow)
				UPDATE nbb_timeonline_date SET timeonline = timeonline + @TimeOnlineDay WHERE acc=@memb___id AND date=Convert(Varchar,@timenow,112)
				IF @@ROWCOUNT = 0
					BEGIN
						INSERT INTO nbb_timeonline_date (acc, timeonline, date) VALUES (@memb___id, @TimeOnlineDay, Convert(Varchar,@timenow,112))
					END
					
				SET @TimeOnlineYesterday = DATEDIFF(minute, @connecttime, DATEADD(day, DATEDIFF(day, 0, @timenow), 0))
				UPDATE nbb_timeonline_date SET timeonline = timeonline + @TimeOnlineYesterday WHERE acc=@memb___id AND date=Convert(Varchar,DATEADD(day, -1, @timenow),112)
				IF @@ROWCOUNT = 0
					BEGIN
						INSERT INTO nbb_timeonline_date (acc, timeonline, date) VALUES (@memb___id, @TimeOnlineYesterday, Convert(Varchar,DATEADD(day, -1, @timenow),112))
					END
			END
		ELSE
			BEGIN
				SET @TimeOnlineDay = DATEDIFF(minute, @connecttime, @timenow)
				UPDATE nbb_timeonline_date SET timeonline = timeonline + @TimeOnlineDay WHERE acc=@memb___id AND date=Convert(Varchar,@timenow,112)
				IF @@ROWCOUNT = 0
					BEGIN
						INSERT INTO nbb_timeonline_date (acc, timeonline, date) VALUES (@memb___id, @TimeOnlineDay, Convert(Varchar,@timenow,112))
					END
			END
		-- Online time end
	end
end