繁体   English   中英

为表运行存储过程

[英]Running a stored procedure for a Table

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

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

---- 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

通过提供的信息,我可以看到您的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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM