简体   繁体   中英

Get scalar value from SELECT statement in stored proc, from within a stored proc

I know the preferred method for returning scalar values from stored procs is either using RETURN or an OUTPUT parameter. But lets say that I have a stored proc that returns the value using a select statement:

CREATE PROC spReturnNumber AS

SELECT 1

Is it possible to get this value from within another stored proc?

CREATE PROC spCheckNumber AS

EXEC spReturnNumber -- <-- get the return value here?

Clarification: I need a solution that doesn't require using an OUTPUT parameter, or using RETURN to return the value.

Thanks in advance.

You could use insert-exec to store the result of a stored procedure in a table:

declare @t table (col1 int)
insert @t exec spReturnNumber
return (select col1 from @t)

The definition of the table has to match the result set of the stored procedure.

Use an OUTPUT parameter instead of (or in addition to, if this procedure is used by other applications) the SELECT .

ALTER PROCEDURE dbo.spReturnNumber
    @Number INT OUTPUT
AS
BEGIN
    SET NOCOUNT ON;

    SET @Number = 1;
    SELECT @Number;
END
GO

CREATE PROCEDURE dbo.spCheckNumber
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @Number INT;
    EXEC dbo.spReturnNumber @Number = @Number;
    SELECT @Number;
END
GO

If you can't change the original procedure, but you know its output will remain static, you could use a #temp table.

CREATE PROCEDURE dbo.spCheckNumber
AS
BEGIN
    SET NOCOUNT ON;

    CREATE TABLE #n(i INT);
    INSERT #n(i) EXEC dbo.spReturnNumber;

    DECLARE @Number INT;
    SELECT @Number = i FROM #n;
END
GO

You can't get the SELECT value from "parent" procedure but you can get the return value like this:

CREATE PROC A AS
BEGIN
    DECLARE @ret int

    EXEC @ret = spReturnNumber

    RETURN @ret
END

Per OP's request, the PostgreSQL way to do this. The first function, foo() just returns an INT. The following functions, bar() and baz() call foo() , in straight SQL, as well as in PL/pgSQL, respectively.

CREATE FUNCTION foo() RETURNS INT AS $$
    SELECT 1
$$ LANGUAGE sql;

CREATE FUNCTION bar() RETURNS INT AS $$
    SELECT foo()
$$ LANGUAGE sql;

CREATE FUNCTION baz() RETURNS INT AS $$
DECLARE
    x INT;
BEGIN
    SELECT INTO x foo();
    RETURN x;
END
$$ LANGUAGE plpgsql;

db=# SELECT foo();
foo
-----
1
(1 row)

db=# SELECT bar();
bar
-----
1
(1 row)

db=# select baz();
baz
-----
1
(1 row)

If you are unable to change the proc being called.. place the result set in a temp table [or table variable]:

CREATE TABLE #results (val INT)
   DECLARE @someval int
   INSERT #results
     EXEC dbo.spCheckNumber 

   SELECT @someval =val from  #results

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM