2013-10-08 60 views
0

我有id_table中的id个数,我需要为table1中至少有多少行运行此过程。我正在使用while循环来运行循环,直到table1中的计数完成,但任何人都可以告诉我每次如何更改@ID。使用表数据作为参数运行存储过程

如果任何人都可以告诉我如何在C#中做也将是好的。

declare @ID INT 
declare @noRun1 INT 
declare @howTime INT 

set @noRun1=1 
set @howTime = (select count(*) from table1) 
set @ID =(select top 1 id from id_table) 

while (@noRun1<[email protected]) 
begin 
    EXEC proc_run @ID 
set @[email protected]+1 
end 
+0

你使用的是什么版本的SQL服务器?可以[TABLE-VALUED PARAMETERS](http://msdn.microsoft.com/en-us/library/bb510489%28SQL.100%29.aspx)是一个选项吗? – GarethD

回答

1

试试这个

DECLARE @uniqueId int 
DECLARE @TEMP TABLE (uniqueId int) 
-- Insert into the temporary table a list of the records to be updated 
INSERT INTO @TEMP (uniqueId) SELECT uniqueId FROM myTable 

-- Start looping through the records 
WHILE EXISTS (SELECT * FROM @TEMP) 
BEGIN 
-- Grab the first record out 
SELECT Top 1 @uniqueId = uniqueId FROM @TEMP 
PRINT 'Working on @uniqueId = ' + CAST(@uniqueId as varchar(100)) 
-- Perform some update on the record 
EXEC proc_run @uniqueId 
-- Drop the record so we can move onto the next one 
DELETE FROM @TEMP WHERE uniqueId = @uniqueId 
END 
1

所以,你要执行为表中的每个ID的存储过程? 重写您对ID的选择,以便您可以跳过多行。事情是这样的:

while (@noRun1 <= @howTime) 
begin 
    select @ID = id from 
     (select id, (ROW_NUMBER() over (order by id)) as numrow from id_table) as tab 
    where numrow = @noRun1 

    EXEC proc_run @ID 

    set @noRun1 = @noRun1 + 1 
end 

如果您正在使用SQL Server 2008+你可以重写你的存储过程来接受表值参数,通过ID的整个列表,只执行一次。看看这个例子:http://technet.microsoft.com/en-us/library/bb510489.aspx

相关问题