调用存储过程并从另一个存储过程传递参数

时间:2009-10-21 09:52:13

标签: sql stored-procedures

这是我的存储过程,它根据作为XML参数传递给它的数组删除行:

BEGIN

DECLARE @docHandle int
EXEC sp_xml_preparedocument @docHandle OUTPUT, @XMLDoc

DELETE Comments WHERE 
       ID IN (SELECT * FROM OPENXML(@docHandle, '/values/value1', 2) WITH (value1 INT '.'))

EXEC sp_xml_removedocument @docHandle
END

现在我要调用另一个存储过程(执行分层删除,它接收ID参数)而不是DELETE

我该怎么做?

更新:这是我的第二个SP:

(
    @ID int
)
AS
IF @ID<>1 
BEGIN   
    CREATE TABLE #nodesC (id int primary key)
    INSERT INTO  #nodesC (id) VALUES (@ID )

    WHILE @@rowcount > 0
        INSERT INTO #nodesC 
        SELECT child.ID  
        FROM Comments child
        INNER JOIN #nodesC parent ON child.ParentId = parent.id
        WHERE child.ID  NOT IN (SELECT id FROM #nodesC)

    DELETE
    FROM Comments
    WHERE ID  IN (SELECT id FROM #nodesC)

END

2 个答案:

答案 0 :(得分:0)

您无法直接将数组作为参数传递。所以:

  • 传入XML并在第二个存储过程中解析
  • 使用表数据类型(SQL Server 2008)
  • 在解析的XML中,每个ID多次调用第二个存储过程(错误,此处为完整性)

否则,关于如何解决这个问题的权威文章是Erland Sommarskog的Arrays and Lists in SQL Server 2005

答案 1 :(得分:0)

您需要一个光标。

DECLARE c CURSOR LOCAL FORWARD_ONLY FOR SELECT ... FROM OPENXML(...) WITH(...)
OPEN c
WHILE 1 <> 0 BEGIN
    FETCH c INTO ...
    IF @@fetchstatus <> 0 BREAK
    EXEC ...
END
CLOSE c
DEALLOCATE c