优化代码

时间:2013-03-28 09:35:45

标签: sql database

我已经为小型数据库编写了这段代码但是知道数据库大小已经增加,它显示超时error.plz帮助优化它 以下是代码: -

IF OBJECT_ID('Temp_expo') is not null
begin 
    drop table Temp_expo
end

set @query3 =  'SELECT SPCT_ID_REL_LOW,SPCT_ID_REL_HIGH,ROW_NUMBER() over (order by PDBC_PFX) as TempId  

INTO Temp_expo  
FROM ['+ @FCTServer +'].['+@FCTDBName+'].dbo.CMC_SPCT_SUPP_CONV  
where  SPCT_ID_REL_LOW <> '''' and SPCT_ID_REL_HIGH <> '''''

exec (@query3)

Select @minCount= min(TempId) from Temp_expo   
Select @maxCount= max(TempId) from Temp_expo  

create table #ICD9SPCT
(
    ICD9Code varchar(200)
} 

while @minCount<=@maxCount 
begin
    select @low=SPCT_ID_REL_LOW,@high=SPCT_ID_REL_HIGH 
    from Temp_expo 
    where TempId=@minCount 
    group by SPCT_ID_REL_LOW,SPCT_ID_REL_HIGH

    set  @loworder = (select ISNULL(OrderId,0) from FCT_ICD9_Diag_ORDER where ICD9=@low)
    set  @highorder = (select ISNULL(OrderId,0) from FCT_ICD9_Diag_ORDER where ICD9=@high)


    insert into #ICD9SPCT 
    select ICD9 from FCT_ICD9_Diag_ORDER ordert
    left join #ICD9SPCT icdorder on ordert.ICD9 = icdorder.ICD9Code
    where OrderId between @loworder and @highorder and icdorder.ICD9Code is null

    set @minCount = @minCount+1;
end

1 个答案:

答案 0 :(得分:0)

如果这是针对SQL SERVER的,您可以尝试一些基本提示: 使用:每次选择后使用WITH(NOLOCK)。 即 从FCT_ICD9_Diag_ORDER ordert WITH(NOLOCK)中选择ICD9     在ordert.ICD9 = icdorder.ICD9Code上左连接#ICD9SPCT icdorder     其中@loworder和@highorder与icdorder.ICD9Code之间的OrderId为空

您也可以尝试将临时表更改为变量表,只需更改#为@:

创建表@ ICD9SPCT (     ICD9Code varchar(200) }

但是,您正在使用的WHILE循环可能是导致问题的主要原因。