简体   繁体   English

为表运行存储过程

[英]Running a stored procedure for a Table

I am trying to run a stored procedure for a table as opposed to one row . 我正在尝试为一个表而不是一行运行一个存储过程。 I choose a stored procedure as I need to insert records into a table and do some updates. 我选择一个存储过程,因为我需要将记录插入表中并进行一些更新。 This method seems to be hanging. 此方法似乎正在挂起。 I looked at the explain plan but I think something is wrong with my logic and it processes one record and stops. 我看了看解释计划,但我认为我的逻辑出了点问题,它处理一条记录并停止。

This is the code I have so far . 这是我到目前为止的代码。 My stored procedure runs like a beast and I dont think that is the problem. 我的存储过程像野兽一样运行,我不认为这是问题所在。

---- 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 SQL SERVER 2005

GO

With the provided information I can see there your While Loop syntax is wrong... 1st you havent enclosed operation in the while loop in BEGIN END block, 2nd You have an infinite while loop which will keep executing since you are not reducing the number of records in you temp table each time your while loop executes. 通过提供的信息,我可以看到您的While循环语法错误...第一,您没有在BEGIN END块的while循环中进行封闭操作,第二,您有一个无限的while循环,它将继续执行,因为您没有减少每当您的while循环执行时,都会在您的临时表中记录。 try something like this... 尝试这样的事情...

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