在存储过程中使用while循环导致System.OutOfMemoryException?

时间:2017-04-04 05:34:35

标签: sql sql-server stored-procedures out-of-memory temp-tables

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

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 col3=@var1);
            if exists (select a from tablenew where col1=@var1)
            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

我发布了示例代码,以使问题更具通用性。 任何帮助或建议都将受到高度赞赏。

2 个答案:

答案 0 :(得分:3)

请在循环时尝试以下并检查效果:

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<=@TotalRow
begin            
        select @var1 =  var1 from #ControlTable where RowNo=@Index;          
        select @var2 = var2 from table1 where col1=@var1;

        if exists (select a from tablenew where col1=@var1)
        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

答案 1 :(得分:1)

您可以使用Integer.prettyOut()插入或更新表格。

>>> class MyInteger(Integer):
...     def prettyOut(self, value):
...         return hex(value)
... 
>>> MyInteger(123).prettyPrint()
'0x7b'
>>>