2017-04-04 126 views
1

我一直在努力与System.OutOfMemoryException。我已经看到了一些解决方案,但都说你需要更多的RAM。我怀疑它是否由于代码效率低下。所以让我分享一下我的问题。
我有10个不同的表,每个表中有5k条记录,我需要从每个表中选择一个列并构建一个新表。我能够插入大约1.5k条记录,但随后执行停止,并且“System.OutOfMemoryException” 。 我while循环看起来像是否在存储过程中使用while循环导致System.OutOfMemoryException?

ALTER PROCEDURE Sp_sample 
As 
    Select col1 
    into 
    #ControlTable 
    from 
    tab1 

while exists(select * from #ControlTable) 
    begin 

      (select count(*) from #ControlTable); 
      select @var1 = (select top 1 col1 from #ControlTable);   
      select @var2 = (select top 1 col2 from table1 where [email protected]); 
      if exists (select a from tablenew where [email protected]) 
      begin    
       update tablenew set col2 = @var2 where col1 = @var1 
      end 
      else 
      begin   
       insert into tablenew values (@var1,@var2) 
      end 
      delete from #ControlTable where col1 = @var1; 
    end 
Begin 

我已经发布的示例代码,使问题更通用。 任何帮助或建议将不胜感激。

+0

你的意思是'select @ var1 =(从#ControlTable选择top 1 col1);'? – artm

+1

我觉得你正在压倒这个任务,很容易用[合并语句](https://technet.microsoft.com/en-us/library/bb522522(v = sql.105).aspx)来完成。另外,有些部分不会像'(从#ControlTable选择count(*)');' –

+1

同意Jorge--'(从#ControlTable选择count(*));'将生成一个单独的*结果集*每次循环迭代。所以,如果你正在谈论5000行,你将会生成5000个结果集供客户端系统处理。 –

回答

3

请尝试以下while循环和检查性能:

ALTER PROCEDURE Sp_sample 
As 
Select col1, ROW_NUMBER() OVER(Order By col1) AS RowNo 
into 
#ControlTable 
from 
tab1 

DECLARE @Index INT=1; 
DECLARE @TotalRow INT=0; 

SELECT @TotalRow=COUNT(col1) FROM #ControlTable 

while @Index<[email protected] 
begin    
     select @var1 = var1 from #ControlTable where [email protected];   
     select @var2 = var2 from table1 where [email protected]; 

     if exists (select a from tablenew where [email protected]) 
     begin    
      update tablenew set col2 = @var2 where col1 = @var1 
     end 
     else 
     begin   
      insert into tablenew values (@var1,@var2) 
     end 
     SET @Index = @Index+1; 
end 
Begin 
+0

谢谢@Sandip。它为我工作。 – Hitsa00

1

你可以使用MERGE插入或更新表。

Select col1, max(col2) AS col2 into #ControlTable from tab1 GROUP BY col1 

MERGE tablenew AS T 
USING #ControlTable AS S 
ON (T.col1 = S.col1) 
WHEN NOT MATCHED BY TARGET 
    THEN INSERT(col1, col2) VALUES(S.col1, S.col2) 
WHEN MATCHED 
    THEN UPDATE SET T.col2 = S.col2