为查询中的每一行调用存储过程

时间:2014-06-24 10:44:25

标签: sql sql-server tsql

我试图在循环中为查询中的每条记录调用存储过程。

这就是我现在所拥有的:

WITH X AS (  
SELECT customerid FROM DBcustomers  
)  
WHILE(EXISTS (SELECT * FROM X))  
BEGIN  
    SELECT TOP 1 @Id = customerid FROM X  
    EXEC [dbo].[AnotherSP] @Id , 1
    DELETE FROM X WHERE customerid = @Id  
END  

,但这不会编译。

3 个答案:

答案 0 :(得分:1)

我想你想这样做UPDATE:

UPDATE ProductTable SET IsActive = 1 
  WHERE customerid  IN (SELECT customerid FROM DBcustomers)    

或针对您编辑的问题使用游标:

DECLARE @id BIG
DECLARE Customers CURSOR 
FOR SELECT customerid FROM DBcustomers 

OPEN Customers FETCH NEXT FROM Customers INTO @id

WHILE @@FETCH_STATUS = 0
BEGIN
   EXEC [dbo].[AnotherSP] @id , 1
   FETCH NEXT FROM Customers INTO @id
END
CLOSE Customers
DEALLOCATE Customers

答案 1 :(得分:0)

UPDATE  productTable
SET     isActive = 1
WHERE   customerId IN
        (
        SELECT  customerId
        FROM    dbCustomers
        )

<强>更新

DECLARE cr_customer CURSOR
FOR
SELECT  customerId
FROM    dbCustomers

DECLARE @id INT

FETCH   NEXT
FROM    cr_customer
INTO    @id

WHILE @@FETCH_STATUS = 0
BEGIN
        EXEC anotherSP @id , 1
        FETCH   NEXT
        FROM    cr_customer
        INTO    @id
END

CLOSE   cr_customer

DEALLOCATE
        cr_customer

答案 2 :(得分:0)

这样的事可能会这样做:

DECLARE @Id INT;
SELECT TOP 1 @Id = customerid FROM DBcustomers ORDER BY customerid;
WHILE @Id IS NOT NULL  
BEGIN  
    EXEC [dbo].[AnotherSP] @Id, 1;
    DECLARE @LastId INT;
    SELECT @LastId = @Id;
    SELECT @Id = NULL;
    SELECT @Id = customerid FROM DBcustomers WHERE customerId > @LastId ORDER BY customerid;
END;