I wanted to implement a validation in my SQL stored procedure that’s designed to create new users. I wanted to validate that a new user can’t use the same username as another user. This is my current stored procedure:
ALTER PROCEDURE NewUserCreation @Login NVARCHAR(50), @Password NVARCHAR(50), @FirstName NVARCHAR(40), @LastName NVARCHAR(40), @DOB DATE(10), @Email NVARCHAR(100), @Phone varchar(10), @Address NVARCHAR(250), AS BEGIN SET NOCOUNT ON INSERT INTO dbo.[USERS] (USERNAME, PASSWORDHASH, USER_F_NAME, USER_L_NAME, USER_DOB, USER_EMAIL) VALUES(@Login, HASHBYTES('SHA2_512', @Password), @FirstName, @LastName, @Email) END
I assume I need to do something using an if statement that takes the value entered from the user in @login, and cross checks it with the USERS table’s username column. Any guidance on the best approach?
Advertisement
Answer
This is what I would do
INSERT INTO dbo.[USERS] (USERNAME, PASSWORDHASH, USER_F_NAME, USER_L_NAME, USER_DOB, USER_EMAIL) SELECT @Login, HASHBYTES('SHA2_512', @Password), @FirstName, @LastName, @Email WHERE NOT EXISTS (SELECT 1 FROM dbo.[USERS] WHERE USER_EMAIL = @Email); IF @@ROWCOUNT = 0 BEGIN THROW 51000, 'Duplicate email address not allowed', 1; END;