如何将存储过程中的变量访问到sql查询中

时间:2015-06-16 16:30:44

标签: sql oracle stored-procedures plsql

我想访问存储过程中存在的变量

e.g。

Create or Replace package body ABC
as 

    Procedure XYZ 
    as
    var Number;
    var := 2+3

    END XYZ

END ABC

现在我想在select语句中访问此变量var。调用body.procedure.variable名称有效吗? 例如

select something as new_variable from table_name where ABC.XYZ.var > 10;

2 个答案:

答案 0 :(得分:2)

如果在包标题中声明了包变量,则只能从外部查询中访问它们。

CREATE OR REPLACE PACKAGE TEST is

var  VARCHAR2(10);
 /*or use the function*/
FUNCTION get_var RETURN VARCHAR2;
END TEST;

您可以访问PL / SQL中的yourSchema.test.var

DECLARE
my_var yourSchema.test.var%TYPE;
BEGIN
my_var := yourSchema.test.var;
END;

或使用函数获取SQL中var的值;

select yourSchema.test.get_var from dual;

在包体中,您可以在加载时初始化var的值,或使用该函数返回值。

答案 1 :(得分:0)

您可以在包中添加以下功能,并使用select from dual调用它:

    create or replace function CHECK_FUNC
    return number
    AS
    var number;
    BEGIN
    var := 2+3;
    return var;
    END CHECK_FUNC;
    /
Function created.     

SQL> select 10 from dual where 10 > (select check_func from dual);
  -- 10 > (2+3) condition satisfied. Hence '10' is returned.                                                                                                

        10                                                                                                                  
----------                                                                                                                  
        10                                                                                                                  

SQL> select 10 from dual where 10 < (select check_func from dual);                                                          
        --10 < (2+3) condition NOT satisfied. Hence no rows returned.                                                                                                                        
no rows selected  

更多例子:

 select 'SOMETHING' from dual where 10 > (select check_func from dual); 

    'SOMETHIN                                                                                                                   
    ---------                                                                                                                   
    SOMETHING     


select 'SOMETHING' from dual where 10 < (select check_func from dual); 

no rows selected