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<=@howTime)
begin 
    EXEC proc_run @ID
set @noRun1=@noRun1+1
end
4

2 回答 2

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
于 2013-10-08T13:11:03.367 回答
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

于 2013-10-08T13:59:56.950 回答