我有一个存储过程,它返回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

其他回答

您可以拆分查询吗?将存储的过程结果插入到表变量或临时表中。然后,从表变量中选择2列。

Declare @tablevar table(col1 col1Type,..
insert into @tablevar(col1,..) exec MyStoredProc 'param1', 'param2'

SELECT col1, col2 FROM @tablevar

这里有一个链接,指向一个非常好的文档,它解释了解决您的问题的所有不同方法(尽管其中许多方法不能使用,因为您不能修改现有的存储过程)。

如何在存储过程之间共享数据

Gulzar的答案是可行的(在上面的链接中有文档),但是编写起来会很麻烦(您需要在@tablevar(col1,…)语句中指定所有80个列名。在将来,如果一个列被添加到模式中,或者输出被改变,它将需要在您的代码中更新,否则它将出错。

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

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

我会剪切粘贴原始SP并删除所有列,除了你想要的两列。或。我将返回结果集,将其映射到适当的业务对象,然后LINQ出这两列。

这里有一个简单的答案:

SELECT ColA, ColB
FROM OPENROWSET('SQLNCLI','server=localhost;trusted_connection=yes;','exec schema.procedurename')

SQLNCLI是本地SQL客户端,“localhost”将使它利用您正在执行过程的服务器。

不需要构建临时表或任何其他jazz。