我正在寻找为日志表创建存储过程的答案。下面是我需要编写该SP的场景。
每当用户使用用户唯一的LOGIN-ID登录或注销商店LOG-IN和LOG-OUT时间时。
此外,如果用户以前的会话异常终止或者用户在没有正确注销的情况下关闭应用程序,那么我必须限制用户登录,然后用户需要在下次登录前等待10分钟。
这就是我的尝试:
ALTER PROCEDURE USP_CHECKER(@LOGINID VARCHAR(70))
AS
BEGIN
DECLARE @LASTID INT,@CURRENTTIME DATETIME,@TEMP INT,@HAS VARCHAR(30)
SELECT TOP 1 SLNO, @TEMP=(DATEDIFF(MI,LOGINDATETIME,GETDATE())) FROM TBL_LOGINDETAILS ORDER BY SlNo DESC
SET @HAS=(SELECT LoginID FROM TBL_LOGINDETAILS WHERE LogoutDateTime IS NULL)
IF @HAS IS NOT NULL
BEGIN
IF(@TEMP >= '10' )
BEGIN
SET @CURRENTTIME = (SELECT DATEADD(MI, -10, GETDATE()))
UPDATE TBL_LOGINDETAILS SET LogoutDateTime=@CURRENTTIME WHERE SLNO=@LASTID
END
ELSE
RETURN @LASTID
--PREVENT FROM LOGIN
END
ELSE
INSERT INTO TBL_LOGINDETAILS (LoginID,LoginDateTime,isLogged) VALUES(@LOGINID,GETDATE(),'1')
END
答案 0 :(得分:2)
跳出来的一件事是你有一个名为@TEMP
的变量INT
的变量 - 但你要比较它就好像是一个字符串:
IF(@TEMP >= '10' ) -- unnecessary single quotes! You're comparing against a string literal...
BEGIN
SET @CURRENTTIME = (SELECT DATEADD(MI, -10, GETDATE()))
UPDATE TBL_LOGINDETAILS SET LogoutDateTime=@CURRENTTIME WHERE SLNO=@LASTID
END
这是一个INT - 所以你需要将它与数值进行比较:
IF(@TEMP >= 10) -- **NO** unnecessary single quotes....
BEGIN
UPDATE dbo.TBL_LOGINDETAILS
SET LogoutDateTime = DATEADD(MI, -10, GETDATE())
WHERE SLNO = @LASTID
END
另外 - 我肯定你可以找到比@TEMP
更适合,更有意义和更明显的名称....
答案 1 :(得分:1)
这是我试过的。
USE [DB]
GO
/****** Object: StoredProcedure [dbo].[USP_SetLoginStatus] Script Date: 11/28/2011 10:58:47 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
ALTER PROCEDURE [dbo].[USP_SetLogStatus]
-- Add the parameters for the stored procedure here
@PLoginName Varchar(75)
AS
BEGIN
DECLARE @SNO INT --VARIABLE TO HOLD THE SERAIL NUMBER
,@ISLOGGED BIT --HOLDING IS LOGGED STATUS
,@TIMEDIFF VARCHAR(50) --VARIABLE TO HOLD TIME DIFFERENCE BETWEEN CURRENT LOGIN AND LAST LOG OUT TIME
-- SELECT QUERY FOR GETTING @TIMEDIFF AND SERIAL-NO VALUES FOR USER
SELECT @SNO=[SlNo],@ISLOGGED=[isLogged] ,@TIMEDIFF =DATEDIFF(MI,
(SELECT TOP (1) [LoginDateTime] FROM TBL_LOGINDETAILS WHERE [LogoutDateTime] IS NULL ORDER BY [SlNo] ),
GETDATE()) FROM TBL_LOGINDETAILS WHERE [LoginID]=@PLoginName
--IF USER IS LOGIN FIRST TIME
IF NOT EXISTS( SELECT isLogged FROM TBL_LOGINDETAILS WHERE [LoginID]=@PLoginName)
INSERT INTO TBL_LOGINDETAILS(LoginID,isLogged,LoginDateTime) VALUES(@PLoginName,'1',GETDATE())
ELSE
BEGIN
IF (@TIMEDIFF >=10) --LOGOUT TIME DIFF IS MORE THAN OR EQUALS TO 10 MINUTE
BEGIN
----- UPDATING LOGOUT AND IS LOGGED FIELD
IF(@ISLOGGED =1 )
BEGIN
UPDATE TBL_LOGINDETAILS SET [LOGOUTDATETIME]= (SELECT DATEADD(MI, -10, GETDATE()) ), [isLogged]=0 WHERE [LoginID]=@PLoginName
AND [SlNo]=@SNO
----- INSERTING NEW LOG FOR CURRENT USER
INSERT INTO TBL_LOGINDETAILS([LoginID],[LoginDateTime],[isLogged]) VALUES(@PLoginName,GETDATE(),1)
END
ELSE
UPDATE TBL_LOGINDETAILS SET [LOGOUTDATETIME]= GETDATE() , [isLogged]=0 WHERE [LoginID]=@PLoginName AND [SlNo]=@SNO
END
ELSE
RETURN '0'
END
END