存储过程一个insert exec语句不能嵌套

时间:2014-05-14 11:15:26

标签: sql sql-server

我有以下存储过程调用另一个存储过程dbo.[spGetResult]

;WITH CTE 
AS
(
    SELECT 0 AS [Level],PNLId , PNLParentId, PNLName
    FROM [dbo].[DimPNL]
    WHERE PNLParentId IS NULL 
    UNION ALL
    SELECT CTE.[Level] + 1 ,T1.PNLId,T1.PNLParentId,T1.PNLName 
    FROM [dbo].[DimPNL] AS T1
    INNER JOIN CTE
    ON T1.PNLParentId = CTE.PNLId
)
-- order the results into a #temp table
SELECT *
INTO ##temp
FROM CTE
ORDER BY level desc

DECLARE @PNLName As varchar(MAX)   

DECLARE db_cursor CURSOR FOR  
SELECT PNLName
FROM ##temp 

OPEN db_cursor   
FETCH NEXT FROM db_cursor INTO @PNLName 

WHILE @@FETCH_STATUS = 0   
BEGIN   
       INSERT INTO dbo.[test1]//from here I have a problem 
       Exec  dbo.[spGetResult] @PNLName

       FETCH NEXT FROM db_cursor INTO @PNLName 
END   

CLOSE db_cursor   
DEALLOCATE db_cursor

我总是得到

  

存储过程一个insert exec语句不能嵌套

我看一下here但我不太了解如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

最好的办法是将存储过程重写为表函数。在性能方面,内联函数效果最好,但在功能上重写这样的过程通常更困难。

尽管可以轻松地将大多数存储过程重写为表值函数。

请点击此处了解详情:http://technet.microsoft.com/en-us/library/ms187650(v=sql.105).aspx

一旦你重写了它,就可以将插入嵌入/ select语句。

  

INSERT INTO [TABLE](col1,col2,...)SELECT tvfcol1,tvfcol2,...   来自dbo.func_TVF_blabla(@ param1,@ param2,...)