print error if there is a name already in the table - sql-server

//My code should be something like this
CREATE PROCEDURE REGISTRATION
#USERNAME VARCHAR(20)
AS
BEGIN
BEGIN IF
SELECT USERNAME FROM USERS WHERE USERNAME = #USERNAME
PRINT 'USER ALREADY EXITS'
ELSE
IF #USERNAME = 'NULL'
PRINT 'Fill username'
end
end

Try This :
CREATE PROCEDURE REGISTRATION
#USERNAME VARCHAR(20)
AS
BEGIN
declare #count as int
select #count = COUNT(*) from USER where USERNAME =#USERNAME
if(#count > 0)
print 'USER ALREADY EXITS' -- Record Exists
else
print 'Fill username' -- NULL
end

use exists. Also, formatting gets overlooked and is important
CREATE PROCEDURE REGISTRATION
#USERNAME VARCHAR(20)=''
AS
BEGIN
IF exists(SELECT 1 FROM USERS WHERE USERNAME = #USERNAME)
begin
PRINT 'USER ALREADY EXITS'
end
ELSE
begin
PRINT 'Fill username'
end
end

Related

my stored procedured worlking properly in local mssql but but not in godaddy mylittleadmin

this is my sql code for login when execte it in my local mssql server
working properly but when i exected in godaddy's mylittleadmin is not
alter proc [dbo].[Loginuser]
#Username nvarchar(100),
#Password nvarchar(100)
as
begin
Declare #Retrycount int
Declare #count int
Declare #Accountlocked bit
Declare #Rolename nvarchar(20)
select #Accountlocked = Islocked
from tbl_Userinfo where Email = #Username
if(#Accountlocked = 1)
begin
select 1 as Accountlocked ,0 as authenticated,0 as Retryattempts
end
else
begin
select #count = count(Email) from tbl_Userinfo where Email=#Username and [Password]=#Password
if(#count=1)
begin
update tbl_Userinfo set Retryattempts = 0
where Email = #Username
select 0 as Accountlocked,1 as authenticated,0 as Rertyattempts
UPDATE tbl_Userinfo
SET LastLogin = GETDATE()
WHERE Email = #Username
SELECT #Rolename = RoleName FROM tbl_Roles WHERE RoleId = (select RoleId from tbl_Userinfo where Email=#Username and [Password]=#Password)
SELECT 1 as [ReturnCode], #Username as [Uname], #Rolename as [Roles]
end
else
begin
select #Retrycount = IsNull(Retryattempts,0)
from tbl_Userinfo where Email = #Username
set #Retrycount=#Retrycount+1
if(#Retrycount <= 3)
begin
update tbl_Userinfo set Retryattempts = #Retrycount
where Email = #Username
select 0 as Accountlocked,0 as authenticated,#Retrycount as Retryattempts
end
else
begin
update tbl_Userinfo set Retryattempts = #Retrycount,
Islocked = 1,Lockeddatetime = GETDATE()
where Email = #Username
select 0 as Accountlocked,0 as authenticated,0 as Retryattempts
end
end
end
end
this is output i want
I want output like in given image but it is working correct in local mssql server when i execute it in godaddy's mylitleadmin it is returning null in Roles columns
This is role table
Can any help me with solution please.

T SQL Nested IF...ELSE in BEGIN...END

I would like some guidance on why there are issues with this procedure. I seem to get an error that states "Incorrect syntax near the keyword 'END'."
I've added comments where I think the issues are. labeled (x) and (y) in the in-code-comments. I used DataGrip for syntax highlighting and that's how I know these pairings exist. But I still don't understand why.
I am aware that a CASE statement could solve this issue. But I would like to know why it is not working with IF...ELSE
CREATE PROCEDURE AuthenticateUser(
#UserName NVARCHAR(50),
#Password NVARCHAR(50),
#Result INT OUTPUT
) AS
BEGIN -- Cannot find a corresponding END
SET NOCOUNT ON
DECLARE #userID INT
IF exists(SELECT UserID FROM Users WHERE UserName = #UserName)
BEGIN -- paired with END (y)
SET #userID = (SELECT UserID FROM Users WHERE UserName = #UserName AND Password = dbo.EncryptPassword(#Password, Salt))
IF #userID IS NULL -- Paired with END (x)
SET #Result = 0
ELSE
SET #Result = 1
END -- paired with IF (x)
ELSE
SET #Result = 0
END -- paired with BEGIN (y)
GO
How about try adding a BEGIN and END label on each IF ELSE condition. Something like this.
CREATE PROCEDURE AuthenticateUser
(
#UserName NVARCHAR(50) ,
#Password NVARCHAR(50) ,
#Result INT OUTPUT
)
AS
BEGIN -- Cannot find a corresponding END
SET NOCOUNT ON
DECLARE #userID INT
IF EXISTS ( SELECT 1
FROM Users
WHERE UserName = #UserName )
BEGIN -- paired with END (y)
SET #userID = ( SELECT UserID
FROM Users
WHERE UserName = #UserName
AND Password = dbo.EncryptPassword(#Password,
Salt)
)
IF #userID IS NULL -- Paired with END (x)
BEGIN
SET #Result = 0
END
ELSE
BEGIN
SET #Result = 1
END
END -- paired with IF (x)
ELSE
BEGIN
SET #Result = 0
END
END -- paired with BEGIN (y)
GO
#Edwinj
Nothing wrong in If else block , there is issue in your code
Salt (Password = dbo.EncryptPassword(#Password, Salt)))
Salt is neither it Number not veritable or string so function EncryptPassword will fail with error.

What's wrong with this Registration stored procedure

I'm trying to make a Registration stored procedure and when I execute the code, I get this error. I've googled it but it's more specific message error was not able to find a solution. what can cause issue here? Thanks in advice!
Error:
Msg 156, Level 15, State 1, Procedure SP_Registration, Line 39 [Batch Start Line 9]
Incorrect syntax near the keyword 'SET'.
This is my stored procedure:
-- =============================================
-- Author: <Nika Kalatozi>
-- Create date: <04/07/2017>
-- Description: <Registration Stored Procedure>
-- =============================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[SP_Registration]
#Username NVARCHAR(25),
#Password NVARCHAR(30),
#Email NVARCHAR(35),
#Firstname NVARCHAR(25),
#Lastname NVARCHAR(25),
#Gender NVARCHAR(10),
#Birthdate DATE,
#PhoneNumber NVARCHAR(25),
#PersonalID NVARCHAR(11),
#Result VARCHAR(100) OUTPUT
AS
BEGIN
IF EXISTS(SELECT #Username FROM Users WHERE #Username = #Username)
BEGIN
SET #Result = 'The username you have entered is already in use.'
RETURN;
END
ELSE IF EXISTS(SELECT #Email FROM Users WHERE #Email = #Email)
BEGIN
SET #Result = 'The email you have entered is already in use.'
RETURN;
END
ELSE
BEGIN
INSERT INTO Users(Username, [Password], Email, Firstname, Lastname,
Gender, BirthDate, PhoneNumber, PersonalID)
SET #Result = 'You have been registered successfully.'
RETURN;
END
END
In code
INSERT INTO Users(
...
)
you should specify what to insert:
INSERT INTO Users(
...
) VALUES
(#Username, ...) -- specify values in brakets

Authenticate user in stored procedure

I am new to sql and I am not sure what's wrong with my stored procedure.
User inputs user name & password which are my input parameters and if it is correct then return 'Login Success', if UN is incorrect than return 'Incorrect UN' or if PW is incorrect than return 'Incorrect PW'. In the stored procedure I have an IF Else statement and it is only hitting the first IF statement not other.
Please have a look my stored procedure:
CREATE PROCEDURE [dbo].[AuthenticateUser]
#UserName varchar(15),
#Password varchar(15),
#Role varchar(25) OUTPUT
AS
SET NOCOUNT ON
BEGIN
DECLARE #UN VARCHAR(25)
DECLARE #PW VARCHAR(25)
SELECT #UN = UserName, #PW = Password FROM LogIn
IF (#UN != #UserName COLLATE SQL_Latin1_General_CP1_CS_AS)
BEGIN
SET #Role = 'Incorrect User Name'
END
ELSE
BEGIN
IF (#PW != #Password COLLATE SQL_Latin1_General_CP1_CS_AS)
BEGIN
SET #Role = 'Incorrect Password'
END
ELSE
BEGIN
SET #Role = 'Logged in Successfully'
END
END
SELECT #Role
END
Thank you for your help
You are doing this:
SELECT #UN = UserName, #PW = Password FROM LogIn
IF (#UN != #UserName COLLATE SQL_Latin1_General_CP1_CS_AS)
These comparisions #UN = UserName and #PW = Password should be made in the WHERE clause to help in proper filtering of rows.
Here is the code rewritten (you can change to using your own table name)
Drop Table TestLogin
GO
Create Table TestLogin
(
UserName VarChar (20),
Password VarChar(20)
)
Insert TestLogin Values ('One', 'Two')
GO
Drop PROCEDURE AuthenticateUser
GO
CREATE PROCEDURE AuthenticateUser
#UserName varchar(15),
#Password varchar(15),
#Role varchar(25) OUTPUT
AS
If ((SELECT Count (*) From TestLogin Where UserName COLLATE SQL_Latin1_General_CP1_CS_AS = #Username And Password COLLATE SQL_Latin1_General_CP1_CS_AS = #Password) = 0)
Begin
If ((SELECT Count (*) From TestLogin Where UserName COLLATE SQL_Latin1_General_CP1_CS_AS = #Username) = 0)
Begin
Select #Role = 'Incorrect User Name'
End
Else
Begin
Select #Role = 'Incorrect Password'
End
End
Else
Begin
Select #Role = 'Logged in Successfully'
End
GO
Declare #Role VarChar (100)
Exec AuthenticateUser 'One', 'Two', #Role Output
Print #Role
Exec AuthenticateUser 'One', 'TwoX', #Role Output
Print #Role
Exec AuthenticateUser 'OneX', 'Two', #Role Output
Print #Role
The three examples provided at the end show you how the procedure behaves when you give it a good login, or either parameter is incorrect.
Change it to a SELECT COUNT(1) FROM userLogin.... and then use ExecuteScalar() on the SqlDataReader object.
As a side note, it's not a good idea to store your passwords in the DB in plain text, but hash them instead, preferably with a salt value.
Try this instead:
Create PROCEDURE [dbo].[AuthenticateUser]
#UserName varchar(15),
#Password varchar(15),
#Role varchar(25) OUTPUT
AS
SET NOCOUNT ON
BEGIN
If Not Exists (Select 1 From LogIn Where UserName = #UserName) Set #Role = 'Incorrect UserName'
Else If Not Exists (Select 1 From LogIn Where Password = #Password) Set #Role = 'Incorrect Password'
Else Set #Role = 'Logged in Successfully'
Select #Role
END
Generally it is not good idea to give an attacker a cue "name is OK, now guess PWD". Plus, password should be at least case sensitive. For this purpose:
select #un=username from LogIn
where username=#username
and cast(password as varbinary(max)) = cast(#password as varbinary(max))
if #un is null
set #role = 'UN or PWD is incorrect'
else
set #role = 'Success'
If you want to give hints:
select #un=username from LogIn
where username=#username
if #un is null
set #role = 'UN not found'
else
begin
select #un=username from LogIn
where username=#username
and cast(password as varbinary(max)) = cast(#password as varbinary(max))
if #un is null
set #role = 'password incorrect'
else
set #role = 'Success'
end
P.S.: I hope username is unique in your table.

Stored procedure is not working

I have created a stored procedure to retrieve some details based on the certain values passed to a parameter. THis requires switching between the SQLs to be executed by stored procedure. Following is the code:
USE [DFS]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[DAFS]
#EmailID Nvarchar(128),
#clientID int,
#userType Varchar(50),
#Success numeric output,
#msg varchar(100) output
AS
BEGIN
if #userType='Normal User'
IF EXISTS (SELECT 1 FROM dbo.Allcdn
WHERE EmailID = #EmailID AND ClientID = #clientID)
begin
set #Success=0
set #msg='Carry on ....'
end
else
begin
set #Success=6
set #msg='Not allowed ...'
END
end
else
Begin
IF EXISTS (SELECT 1 FROM dbo.Alcon
WHERE EmailID = #EmailID AND ClientID = #clientID)
BEGIN
set #Success=0
set #msg='Carry on...'
END
END
End
end
END
The entire processing is based on the variable #userType. Not sure why the stored procedure is not compiling.
Formatting is your friend, just with a quick glance, it appears you have too many ENDs -- See SQL Fiddle with working Demo:
CREATE PROCEDURE [dbo].[DAFS]
#EmailID Nvarchar(128),
#clientID int,
#userType Varchar(50),
#Success numeric output,
#msg varchar(100) output
AS
BEGIN
if #userType='Normal User'
IF EXISTS (SELECT 1 FROM dbo.Allcdn
WHERE EmailID = #EmailID AND ClientID = #clientID)
begin
set #Success=0
set #msg='Carry on ....'
end
else
begin
set #Success=6
set #msg='Not allowed ...'
END
else
Begin
IF EXISTS (SELECT 1 FROM dbo.Alcon
WHERE EmailID = #EmailID AND ClientID = #clientID)
BEGIN
set #Success=0
set #msg='Carry on...'
END
END
end

Resources