我有一个存储过程,它返回80列和300行。我要写一个select函数,它能得到2个这样的列。类似的

SELECT col1, col2 FROM EXEC MyStoredProc 'param1', 'param2'

当我使用上面的语法时,我得到了错误:

“无效的列名”。

我知道最简单的解决方案是更改存储过程,但我没有编写它,也不能更改它。

有什么办法能让我如愿以偿吗?

I could make a temp table to put the results in, but because there are 80 columns so I would need to make an 80 column temp table just to get 2 columns. I wanted to avoid tracking down all the columns that are returned. I tried using WITH SprocResults AS .... as suggested by Mark, but I got 2 errors Incorrect syntax near the keyword 'EXEC'.Incorrect syntax near ')'. I tried declaring a table variable and I got the following error Insert Error: Column name or number of supplied values does not match table definition If I try SELECT * FROM EXEC MyStoredProc 'param1', 'param2' I get the error : Incorrect syntax near the keyword 'exec'.


当前回答

要实现这一点,首先你创建一个#test_table,如下所示:

create table #test_table(
    col1 int,
    col2 int,
   .
   .
   .
    col80 int
)

现在执行过程并将值放在#test_table中:

insert into #test_table
EXEC MyStoredProc 'param1', 'param2'

现在你从#test_table中获取值:

select col1,col2....,col80 from #test_table

其他回答

(假设SQL Server)

在T-SQL中处理存储过程结果的唯一方法是使用INSERT INTO…EXEC语法。这样就可以向临时表或表变量中插入数据,并从中选择所需的数据。

对于SQL Server,我发现这工作得很好:

创建一个临时表(或永久表,并不重要),并对存储过程执行insert into语句。SP的结果集应该与表中的列匹配,否则将得到一个错误。

这里有一个例子:

DECLARE @temp TABLE (firstname NVARCHAR(30), lastname nvarchar(50));

INSERT INTO @temp EXEC dbo.GetPersonName @param1,@param2;
-- assumption is that dbo.GetPersonName returns a table with firstname / lastname columns

SELECT * FROM @temp;

就是这样!

正如问题中提到的,在执行存储过程之前很难定义80列的临时表。

另一种方法是根据存储过程结果集填充表。

SELECT * INTO #temp FROM OPENROWSET('SQLNCLI', 'Server=localhost;Trusted_Connection=yes;'
                                   ,'EXEC MyStoredProc')

如果您得到任何错误,您需要通过执行以下查询来启用特定的分布式查询。

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

要使用两个参数执行sp_configure以更改配置选项或运行RECONFIGURE语句,必须授予ALTER SETTINGS服务器级权限

现在可以从生成的表中选择特定的列

SELECT col1, col2
FROM #temp

一个快速的方法是添加一个新参数“@Column_Name”,并让调用函数定义要检索的列名。在你的sproc的返回部分,你会有if/else语句并只返回指定的列,或者如果为空-返回所有。

CREATE PROCEDURE [dbo].[MySproc]
        @Column_Name AS VARCHAR(50)
AS
BEGIN
    IF (@Column_Name = 'ColumnName1')
        BEGIN
            SELECT @ColumnItem1 as 'ColumnName1'
        END
    ELSE
        BEGIN
            SELECT @ColumnItem1 as 'ColumnName1', @ColumnItem2 as 'ColumnName2', @ColumnItem3 as 'ColumnName3'
        END
END

如果你只需要这样做一次,最简单的方法是:

在导入和导出向导中导出到excel,然后将此excel导入到表中。