I have a procedure that checks user input. I want it to be added to my logs when the user logs in. But when I try this way it adds though the login fails.
ALTER PROCEDURE [dbo].[sp_KullaniciGiris]
@username varchar(10),
@pw nvarchar(20)
AS
BEGIN
SELECT*FROM Kullanicilar WHERE username=@username AND
pw=@pw and IsActive=1
END
INSERT INTO LogIslem(Kullanici,LogText,Sayfa,Islem)
VALUES(
@username,
+'username:'+@username+
'pw:'+@pw,
'FormLogin',
'Login'
)
>Solution :
Without having the error message that you are getting and by just looking at the code that you provided, I could give you a few pieces of advice:
- The INSERT INTO statement is outside of the BEGIN END block of your stored procedure.
You may want to rewrite your stored procedure as follows:
ALTER PROCEDURE [dbo].[sp_KullaniciGiris]
@username varchar(10),
@pw nvarchar(20)
AS
BEGIN
-- First, try to find a matching, active user
DECLARE @userExists INT;
SELECT @userExists = COUNT(*) FROM Kullanicilar WHERE username = @username AND pw = @pw AND IsActive = 1;
-- If such a user was found, log the successful login and return the user's information
IF @userExists = 1
BEGIN
INSERT INTO LogIslem (Kullanici, LogText, Sayfa, Islem)
VALUES (@username, 'username:' + @username + ' pw:' + @pw, 'FormLogin', 'Login');
SELECT * FROM Kullanicilar WHERE username = @username AND pw = @pw AND IsActive = 1;
END
END
In this version of your stored procedure, the code first checks whether the user already exists. If the user is found, the code logs the attempt and then returns the user’s information. If no matching user if found, nothing happens and the stored procedure does not return anything, and the event is not logged either.
In this example, you are inserting a password as part of a log entry. This is a bad practice even is the password is hashed or encrypted.