将参数传递给sql server中的存储过程

时间:2014-06-02 13:20:38

标签: sql

我有一个删除SP,它对多个表执行操作并接受3个参数。我有一张包含100条记录的表格,其中包含SP所需的3个参数。

我试图想办法为表中的每一行调用SP并触发SP。

例如:考虑Sp:up_form_delete。表单包含跨多个表存储的数据,并接受参数form_id,account_id和created_date。我有一个带有这些参数的临时表。我需要对临时表中存在的所有记录执行up_form_delete'form_id','account_id','created_date'

有关如何实现这一目标的任何想法?

1 个答案:

答案 0 :(得分:0)

您可以使用遍历所有行的游标,也可以使用每行调用存储过程。

以下是来自MSDN博客的示例:


SET NOCOUNT ON;

DECLARE @vendor_id int, @vendor_name nvarchar(50),
    @message varchar(80), @product nvarchar(50);

PRINT '-------- Vendor Products Report --------';

DECLARE vendor_cursor CURSOR FOR 
SELECT VendorID, Name
FROM Purchasing.Vendor
WHERE PreferredVendorStatus = 1
ORDER BY VendorID;

OPEN vendor_cursor

FETCH NEXT FROM vendor_cursor 
INTO @vendor_id, @vendor_name

WHILE @@FETCH_STATUS = 0
BEGIN
    PRINT ' '
    SELECT @message = '----- Products From Vendor: ' + 
        @vendor_name

    PRINT @message

    -- Declare an inner cursor based   
    -- on vendor_id from the outer cursor.

    DECLARE product_cursor CURSOR FOR 
    SELECT v.Name
    FROM Purchasing.ProductVendor pv, Production.Product v
    WHERE pv.ProductID = v.ProductID AND
    pv.VendorID = @vendor_id  -- Variable value from the outer cursor

    OPEN product_cursor
    FETCH NEXT FROM product_cursor INTO @product

    IF @@FETCH_STATUS <> 0 
        PRINT '         <<None>>'     

    WHILE @@FETCH_STATUS = 0
    BEGIN

        SELECT @message = '         ' + @product
        PRINT @message
        FETCH NEXT FROM product_cursor INTO @product
        END

    CLOSE product_cursor
    DEALLOCATE product_cursor
        -- Get the next vendor.
    FETCH NEXT FROM vendor_cursor 
    INTO @vendor_id, @vendor_name
END 
CLOSE vendor_cursor;
DEALLOCATE vendor_cursor;