嵌套存储过程

时间:2011-10-26 23:27:39

标签: sql sql-server sql-server-2008

我需要创建一个存储过程,它将返回一个代码列表,然后我需要调用另一个存储过程来逐个查看每个代码。

我该怎么做?

CREATE PROCEDURE [dbo].[paBltBuscarBoletasASA] @id_Asa int  
AS
DECLARE @Query int, @Contador int 
SET @Contador = 0
BEGIN
      SET NOCOUNT ON;  
      SET @Query = (
                SELECT 
                    localizacion.c_Fk_IdBoleta
                FROM 
                    Blt_Boleta as boleta, Fnc_Localizacion as localizacion
                WHERE 
                    boleta.c_Pk_IdBoleta = localizacion.c_Fk_IdBoleta AND
                    localizacion.si_CodAsa = @id_Asa) //This query give the list of Codes. For example 45550711, 40480711, 80110711... etc

    exec dbo.paBltMarcarErroresBoleta @Query //And here I need send one by one that list of Codes
END

2 个答案:

答案 0 :(得分:1)

您可以考虑添加标量函数并在查询中调用它,例如:

SELECT 
    localizacion.c_Fk_IdBoleta,
    dbo.checkCode(localizacion.c_Fk_IdBoleta) as Check
FROM 
    Blt_Boleta as boleta, Fnc_Localizacion as localizacion
WHERE 
    boleta.c_Pk_IdBoleta = localizacion.c_Fk_IdBoleta AND
    localizacion.si_CodAsa = @id_Asa

答案 1 :(得分:-1)

为您设置的等于@Query的查询声明CURSOR,然后在WHILE @@ FETCH_STATUS = 0循环中将每个后续值插入变量。然后将@Query变量传递给您当前正在执行的第二个存储过程。这是一个例子:

DECLARE myCursor CURSOR FOR
SELECT localizacion.c_Fk_IdBoleta
FROM Blt_Boleta as boleta, Fnc_Localizacion as localizacion
WHERE boleta.c_Pk_IdBoleta = localizacion.c_Fk_IdBoleta AND 
localizacion.si_CodAsa = @id_Asa

OPEN myCursor

FETCH NEXT FROM myCursor INTO @Query

WHILE @@FETCH_STATUS = 0
BEGIN
    exec dbo.paBltMarcarErroresBoleta @Query
    //do additional processing

FETCH NEXT FROM myCursor INTO @Query
END

CLOSE myCursor
DEALLOCATE myCursor

其他光标帮助:http://msdn.microsoft.com/en-us/library/ms180169.aspx