SQL Server优化存储过程中的代码

时间:2010-08-11 18:26:11

标签: sql sql-server tsql

比较下面的两个代码,两者都是相同的,但略有不同:

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

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

你认为第一个比性能更快,我的意思是,第一个代码使用临时表(#TempUser)来存储来自真实表的3个字段。第二个代码,逐个选择真实表中的所有字段。

哪种代码最佳优化?

3 个答案:

答案 0 :(得分:5)

首先 - 如果传递的参数可能为null,则需要设置默认值。例如:

@usu_ds_email varchar(100) = null
...

否则,你的进一步调查将永远不会发挥作用 - 程序将失败。

第二 - 只需运行直接更新。看起来你不必要地来回推送大量数据。例如,您不需要从要更新的表中创建临时表,然后右转并从刚创建的临时表中更新表。

ALTER procedure [dbo].[SP_USUARIOS_UPDATE]
@usu_ds varchar(100),
@usu_dt_lst_log datetime,
@usu_ds_senha varchar(255) = null,
@usu_ds_email varchar(100) = null
as
begin

    update Usuarios 
    set usu_dt_lst_log = @usu_dt_lst_log,
        usu_ds_senha = isnull(@usu_ds_senha, usu_ds_senha),
        usu_ds_email = isnull(@usu_ds_email, usu_ds_email)
    where usu_ID = @usu_ds

end

答案 1 :(得分:3)

第三种方式......

ALTER procedure [dbo].[SP_USUARIOS_UPDATE] 
@usu_ds varchar(100), 
@usu_dt_lst_log datetime, 
@usu_ds_senha varchar(255) = null, 
@usu_ds_email varchar(100) = null 
as 
begin 

update x 
set x.usu_dt_lst_log = @usu_dt_lst_log, 
    x.usu_ds_senha = ISNULL(@usu_ds_senha, x.usu_ds_senha), 
    x.usu_ds_email = ISNULL(@usu_ds_email, x.usu_ds_email)
from Usuarios x where x.usu_ds = @usu_ds
end 

答案 2 :(得分:0)

哪一个跑得更快?设置一个分析器,运行两个,并获得一些真实的数据:然后你就会知道。

然而,根据我以前的经验,Temp Table一直对我来说更快。