I need some help with this procedure:
What its supposed to do is try to insert a new user if there is no other with same NAME.
If there is a already an user, it should rollback else commit. But it doesn’t work, it commits anyway.
Any suggestions?
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [dbo].[SP_USUARIOS_INSERT]
@usu_ds varchar(50),
@usu_dt_create datetime,
@usu_dt_lst_log datetime,
@usu_ds_senha varchar(255),
@usu_ds_email varchar(100)
as
begin
declare @varCheckUser varchar(100) = null;
set @varCheckUser = (select COUNT(usu.usu_Ds) from Usuarios usu where usu.usu_ds = @usu_ds);
begin transaction
insert into Usuarios(usu_ds,usu_dt_create,usu_dt_lst_log,usu_ds_senha,usu_ds_email) values(@usu_ds,@usu_dt_create,@usu_dt_lst_log,@usu_ds_senha,@usu_ds_email)
if (@varCheckUser <> null)
begin
RAISERROR('User already exists',16,1)
rollback transaction
return
end
else
begin
commit transaction
end
end
I don’t think that @varCheckUser will ever be NULL, if there is no row it will be 0
this will make it 0
also you check like this for NULL
why don’t you do something like this
then check that it is not 1
why do you need the tran? Just do something like this
Probably a good idea to make usu_ds a
primary keyor add aunique constraint, that way nobody can update their user name to something that exists and nobody can by mistake use SSMS and change a user name to something that is already in the table