Comparing two codes below,both do the same,but with slighty differences:
ALTER procedure [dbo].[SP_USUARIOS_UPDATE]
@usu_ds varchar(100),
@usu_dt_lst_log datetime,
@usu_ds_senha varchar(255),
@usu_ds_email varchar(100)
as
begin
declare @usu_ID int;
create table #TempUser
(
UsuID int,
Senha varchar(255),
Email varchar(100)
)
select Usuarios.usu_ID as UsuID,Usuarios.usu_ds_senha as Senha,
Usuarios.usu_ds_email as Email into #TempUser from Usuarios where Usuarios.usu_ds = @usu_ds
if(@usu_ds_senha is null)
begin
set @usu_ds_senha = (select #TempUser.Senha from #TempUser);
end
if(@usu_ds_email is null)
begin
set @usu_ds_email = (select #TempUser.Email from #TempUser);
end
set @usu_ID = (select #TempUser.UsuID from #TempUser);
update Usuarios set usu_dt_lst_log =
@usu_dt_lst_log,usu_ds_senha = @usu_ds_senha,usu_ds_email = @usu_ds_email where usu_ID = @usu_ID
end
AND
ALTER procedure [dbo].[SP_USUARIOS_UPDATE]
@usu_ds varchar(100),
@usu_dt_lst_log datetime,
@usu_ds_senha varchar(255),
@usu_ds_email varchar(100)
as
begin
declare @usu_ID int;
if(@usu_ds_senha is null)
begin
set @usu_ds_senha = (select Usuarios.usu_ds_senha from Usuarios where Usuarios.usu_ds = @usu_ds);
end
if(@usu_ds_email is null)
begin
set @usu_ds_email = (select Usuarios.usu_ds_email from Usuarios where Usuarios.usu_ds = @usu_ds);
end
set @usu_ID = (select Usuarios.UsuID from Usuarios where Usuarios.usu_ds = @usu_ds);
update Usuarios set usu_dt_lst_log =
@usu_dt_lst_log,usu_ds_senha = @usu_ds_senha,usu_ds_email = @usu_ds_email where usu_ID = @usu_ID
end
Do you think the first is faster than second in performance,i mean,first code use temp table (#TempUser) to store 3 fields from the real table.Second code,select all fields from the real table one by one.
What code is best optimized?
First — if it’s possible for your passed parameters to be null, you need to set defaults. For example:
Otherwise, your null checks further down will never come into play — the procedure will just fail.
Second — just run a direct update. It seems like you’re pushing a lot of data back and forth unnecessarily. E.g., you don’t need to create a temp table from the table you’re going to update, and then turn right around and update your table from the temp table you just created.