运行表的存储过程

时间:2013-11-25 21:06:54

标签: sql sql-server sql-server-2005

我正在尝试为一个表而不是一行运行存储过程。我选择一个存储过程,因为我需要将记录插入表中并进行一些更新。 这种方法似乎悬而未决。我查看了解释计划,但我认为我的逻辑有问题,它处理一条记录并停止。

这是我到目前为止的代码。我的存储过程像野兽一样运行,我不认为这是问题所在。

---- Create a driver table for the stored procedure to run off .
drop table #Driver_Table

select col1, col2
IDENTITY( int ) AS idcol
INTO #Driver_Table
FROM CUSTOMER 
--- Contains about 37 k records 

--- Index added for performance 
CREATE CLUSTERED INDEX IDX_C_Driver_Table_UserID ON #Driver_Table(idcol)

-- Define the last customer ID to be handled
DECLARE @LastCustomerID INT
SET @LastCustomerID = 0

--- Other parameter the queries will use  
DECLARE @idcol INT 
DECLARE @col1 datetime
DECLARE @col2 varchar(200)

SET @idcol= 0

-- Iterate over all customers
BEGIN 

-- Get next customerId
SELECT TOP 1 @idcol = idcol FROM #Driver_Table
WHERE idcol > @LastCustomerID 

select TOP 1 @col1=col1
FROM #Driver_Table
WHERE idcol > @LastCustomerID 

select TOP 1 @col2=col2
FROM #Driver_Table
WHERE idcol > @LastCustomerID 

---- To get the process to end when last customer is processed.
WHILE @col2 NOT NULL

-- call your sproc
EXEC SP @col1,@Col2

-- set the last customer handled to the one we just handled
SET @LastCustomerID = @idcol
SET @col2 = NULL

-- select the next customer to handle 
SELECT TOP 1 @col2 = col2
FROM #Driver_Table
WHERE idcol > @LastCustomerID

END

SQL SERVER 2005

GO

1 个答案:

答案 0 :(得分:1)

使用提供的信息,我可以看到你的While循环语法是错误的...首先你没有在BEGIN END块中的while循环中包含操作,第二个你有一个无限的while循环,它将继续执行,因为你没有减少每次while循环执行时,临时表中的记录数。尝试这样的事情......

WHILE (EXISTS (SELECT * FROM #Driver_Table))

 BEGIN

    SELECT TOP 1 @idcol = idcol, @col1=col1, @col2=col2
    FROM #Driver_Table


    EXEC SP @col1,@Col2

    DELETE FROM #Driver_Table 
    WHERE idcol = @idcol;


 END