如何在不使用 temp 的情况下从存储过程的结果集中选择一列。桌子?
我在 SQL Server 2005 中有一个存储过程。它在一行中返回三个变量,如下(极其简化)示例:
CREATE PROCEDURE proc1
AS
DECLARE @col1 VARCHAR(4)
DECLARE @col2 VARCHAR(4)
DECLARE @col3 VARCHAR(4)
SET @col1 = 'val1'
SET @col2 = 'val2'
SET @col3 = 'val3'
SELECT @col1 col1, @col2 col2, @col3 col3
GO
在外部应用程序中,我需要执行存储过程并处理三个值之一。由于此应用程序的限制,它将始终仅使用第一列。
因此,我正在寻找一种将过程的结果集限制为一列或重新排列列的顺序的方法。
IIRC MySQL支持如下子查询,但SQL Server不支持:
SELECT col1 FROM (EXEC proc1)
我知道我可以使用临时表(或表变量)来缓冲结果,然后选择一列,但我希望有一种更“简洁”的方式比这个:
CREATE TABLE #tmp (col1 VARCHAR(4) NOT NULL, col2 VARCHAR(4) NOT NULL, col3 VARCHAR(4) NOT NULL)
INSERT INTO #tmp EXEC proc1
SELECT col2 FROM #tmp
DROP TABLE #tmp
预先感谢您提供的任何提示,
帕特里克
I have a stored procedure in SQL Server 2005. It returns three variables in one single line, like this (extremely simplified) example:
CREATE PROCEDURE proc1
AS
DECLARE @col1 VARCHAR(4)
DECLARE @col2 VARCHAR(4)
DECLARE @col3 VARCHAR(4)
SET @col1 = 'val1'
SET @col2 = 'val2'
SET @col3 = 'val3'
SELECT @col1 col1, @col2 col2, @col3 col3
GO
In an external application, I need to execute the stored procedure and process one of the three values. Due to limitation in this application, It will always only use the very first column.
So, what I'm looking for is a way to limit the result set of the procedure to one column or rearrange the order of the columns.
IIRC MySQL supports subqueries like the following, but SQL Server does not:
SELECT col1 FROM (EXEC proc1)
I know that I can use a temporary table (or table variable) to buffer the result and then select one column, but I hope that there is a more "condensed" way than this:
CREATE TABLE #tmp (col1 VARCHAR(4) NOT NULL, col2 VARCHAR(4) NOT NULL, col3 VARCHAR(4) NOT NULL)
INSERT INTO #tmp EXEC proc1
SELECT col2 FROM #tmp
DROP TABLE #tmp
Thanks in advance for any hints you can give,
Patrick
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您可以将存储过程转换为表值函数,您可以从中选择任意列。如果您仍然需要存储过程(对于某些其他无法更改的系统),您可以将所有逻辑放入函数中,并让存储过程来调用它。
否则,如果您无法从存储过程中重新定位代码,那么恐怕通过临时表是您能做的最好的事情。
If you could convert the stored proc into a table valued function, you could select arbitrary columns from that. If you still need the stored proc (for some other system that can't be changed), you can put all of the logic in the function, and get the stored proc to call that.
Otherwise, if you can't relocate the code from the stored proc, then going via a temp table is about the best you can do, I'm afraid.