【问题标题】:Return result of SELECT to another procedure [duplicate]将 SELECT 的结果返回到另一个过程 [重复]
【发布时间】:2016-09-01 15:35:44
【问题描述】:

我在将一个过程结果“返回”到另一个过程时遇到问题。

说明:

例如,我们有复杂的 SELECT,其参数放在一个过程中。

USE [myDB]
GO

ALTER PROCEDURE dbo.Procedure1 @today date
AS


SELECT * FROM complex_query

现在它返回很多列,列数和行数取决于 @today 值。

不,我想在 Procedure2

中使用 Procedure1 的结果
USE [myDB]
GO

DECLARE @cntMonth INT = 0;

WHILE @cntMonth < 12  
BEGIN
  SELECT x,y,z FROM result_of_Procedure1
  SET @cntMonth = @cntMonth + 1;
END;

我为什么要这样?
这是因为我正在使用的软件正在连接到数据库,运行程序并将结果获取到前端。所以我必须一直用 SQL 编写代码。
因此,假设软件正在进行一次性连接,我不想每次执行 WHILE 语句时都通过 Procedure1。如何存储Procedure1的效果以通过Procedure2 while循环使用它并防止Procedure1多次运行?

【问题讨论】:

    标签: sql sql-server


    【解决方案1】:
    CREATE TABLE #TempResults
    ( 
      -- put definition of columns returned from your Procedure1 SP here
    )
    
    INSERT INTO #TempResults
    EXEC Procedure1
    
    -- now you have your result from Procedure1 in #TempResults
    -- use it whatever way you want
    SELECT * FROM #TempResults
    
    -- finally drop the temp table when no longer needed
    DROP TABLE #TempResults
    

    【讨论】:

    • 好的,如果第二个用户同时启动这个过程,临时表#TempResults已经存在会不会有问题?
    • 不,每个临时表(使用 # 前缀创建)对于会话/连接都是唯一的。这样两个用户就不会互相搞砸了。
    猜你喜欢
    • 2020-11-17
    • 1970-01-01
    • 1970-01-01
    • 2016-01-28
    • 2011-05-03
    • 1970-01-01
    • 1970-01-01
    • 2021-02-23
    • 1970-01-01
    相关资源
    最近更新 更多