Is it possible to execute a stored procedure over a set without using a cursor?

前端 未结 7 924
遥遥无期
遥遥无期 2020-12-15 18:55

I would like to execute a stored procedure over each row in a set without using a cursor with something like this:

SELECT EXEC dbo.Sproc @Param1 = Table1.i

7条回答
  •  春和景丽
    2020-12-15 19:14

    If you're only using SQL Server 2005 or newer, don't care about backwards compatibility and can convert your code to be in a User-Defined Function (rather than a stored proc) then you can use the new "CROSS APPLY" operator, which does use a syntax very similar to what you want. I found here a short intro (of course, you can also read the BOLs and MSDN)

    Supposing your SP returns a single value named out_int, your example could be rewritten as:

    SELECT T.id, UDF.out_int
    FROM 
        Table1 T
    CROSS APPLY
        dbo.fn_My_UDF(T.id) AS UDF
    

    This will retrieve each "id" from Table1 and use it to call fn_My_UDF, the result of which will appear in the final result-set besides the original parameter.

    A variat of "CROSS APPLY" is "OUTER APPLY". They are equivalents of "INNER JOIN" and "LEFT JOIN", but work on joining a table and a UDF (and calling the second at the same time).

    If you must (by explicit order of the pointy-haired boss) use SPs insead, well - bad luck! You'll have to keep with cursors, or try cheating a bit: change the code into UDFs, and create wrapper SPs :D.

提交回复
热议问题