开发者

How to SELECT one column from the result set of a stored procedure without using temp. tables?

开发者 https://www.devze.com 2023-02-07 21:05 出处:网络
I have a stored procedure in SQL Server 2005. It returns three variables in one single line, like this (extremely simplified) example:

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
DRO开发者_运维问答P TABLE #tmp

Thanks in advance for any hints you can give,

Patrick


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号