为表的每一行运行存储过程

时间:2014-06-11 07:27:48

标签: sql tsql stored-procedures

我有一个看起来像这样的表

value_1  value_2  value_3
---------------------------
   1        2        3
   4        5        6
   7        8        9
   ...     ...     ...

我需要为这个表的每一行运行一个存储过程,比如

foreach value_1, value_2, value_3 from my_table
exec spProcedure value_1, value_2, value_3

有办法做到这一点吗?

2 个答案:

答案 0 :(得分:3)

您可以使用光标:

DECLARE @value1 INT,
        @value2 INT,
        @value3 INT 

DECLARE cursorElement CURSOR FOR
            SELECT  value_1, value_2, value_2
            FROM    table


OPEN cursorElement
FETCH NEXT FROM cursorElement INTO @value1, @value2, @value3

WHILE ( @@FETCH_STATUS = 0 )
BEGIN
    exec spProcedure @value1, @value2, @value3

    FETCH NEXT FROM cursorElement INTO @value1, @value2, @value3
END         
CLOSE cursorElement
DEALLOCATE cursorElement

答案 1 :(得分:-1)

另一种方式:

DECLARE @MemoryTable table (
    RowID int,
    value_1 int,
    value_2 int,
    value_3 int
)

INSERT INTO @MemoryTable
SELECT ROW_NUMBER() OVER (ORDER BY value_1) AS RowID, * FROM SampleTable


DECLARE @ctr INT
DECLARE @MaxRownum INT

DECLARE @val1 INT
DECLARE @val2 INT
DECLARE @val3 INT


SET @ctr = 1
SET @MaxRownum = (SELECT COUNT(1) FROM @MemoryTable)


WHILE @ctr <= @MaxRownum
BEGIN

    SELECT @val1 = value_1,
           @val2=value_2,
           @val3=value_3
    FROM @MemoryTable
    WHERE RowID = @ctr

    exec spProcedure @val1, @val2, @val3

    SET @ctr = @ctr + 1
END