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

与世无争的帅哥 提交于 2021-02-07 08:57:20

问题


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.


回答1:


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.




回答2:


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



回答3:


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



回答4:


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)



回答5:


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


来源:https://stackoverflow.com/questions/6641113/get-scalar-value-from-select-statement-in-stored-proc-from-within-a-stored-proc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!