2013-10-08 91 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

相關問題