简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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