将存储过程结果集分离到临时表中

Separate Stored Procedure result sets into Temporary tables

我有一个存储过程 returns 2 个结果集。我正在尝试调用存储过程并将第一个结果集的值插入临时 table,但我无法执行此操作,因为我正在 returning 2 个结果集。

有没有一种方法可以 return 将一个结果集或两个结果集 table 分开临时 table 。我无法更改存储过程。

存储过程结果集1

column a | column b | coulmn c 

存储过程结果集2

column x | column y

我在做的是

DECLARE @ResultSet1Table 
TABLE (
        column a
       ,column b
       ,column c
       )

INSERT INTO @ResultSet1Table 
   EXEC StoredProc

并收到错误消息

Column name or number of supplied values does not match table definition

因为第二个结果集。

好的,这有点骇人听闻:

CREATE PROCEDURE SPMultipleResultsSets
AS

SELECT *
FROM 
    ( VALUES (1),(2),(3),(4)) Vals(Num)

SELECT *
FROM 
    ( VALUES ('ABC'),('DEF'),('GHI'),('JKL')) Strings(string)

您需要打开临时分布式查询:

sp_configure 'Show Advanced Options', 1
GO
RECONFIGURE
GO
sp_configure 'Ad Hoc Distributed Queries', 1
GO
RECONFIGURE
GO

SELECT * INTO #Temp FROM OPENROWSET('SQLNCLI', 'Server=localhost;Trusted_Connection=yes;',
'EXEC DBNAME.dbo.SPMultipleResultsSets')
-- Select Table
SELECT *
FROM #Temp;

Returns:

Num
1
2
3
4

我认为我有一个合理的变通办法。只需添加列即可识别每个结果集。然后将它们与查询分开。看看:

CREATE PROCEDURE usp_test
AS
SELECT  colA = 'A',
        colB = 'B',
        colC = 'C';

SELECT  colX = 'X',
        colY = 'Y',
        '!';
GO

DECLARE @ResultSetTable TABLE(col1 CHAR,col2 CHAR,col3 CHAR);

INSERT INTO @ResultSetTable
    EXEC usp_test

--Set 1
SELECT *
FROM @ResultSetTable
WHERE col3 <> '!'

--Set 2
SELECT *
FROM @ResultSetTable
WHERE col3 ='!'

第 1 组的结果:

col1 col2 col3
---- ---- ----
A    B    C

第 2 组的结果:

col1 col2 col3
---- ---- ----
X    Y    !