以表数据作为参数运行存储过程

时间:2013-10-08 12:56:23

标签: c# sql-server tsql stored-procedures

我在id_table中有多个id,我需要至少为table1中的行数运行此过程。我正在使用while循环运行循环直到count1在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

2 个答案:

答案 0 :(得分: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 :(得分: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