pl / sql选择变量

时间:2015-01-30 22:01:47

标签: oracle plsql

我有一个简单的SQL Server存储过程

CREATE PROCEDURE [dbo].[some_proc]
AS
BEGIN
    DECLARE @CountA INT
    DECLARE @CountB INT
    DECLARE @CountC INT
    DECLARE @CountD INT
    SELECT @CountA = COUNT(*) FROM some_table WHERE Status IN (7,8,9) 
    SELECT @CountB =  COUNT(*)  FROM some_table WHERE Status IN (5)
    SELECT @CountC = COUNT(*) FROM some_table WHERE Status IN (6) 
    SELECT @CountD = COUNT(*) FROM some_table 


    SELECT @CountA AS aCount , @CountB AS bCount , @CountC AS cCount , @CountD AS dCount

END

GO

我们为产品支持SQL Server和Oracle数据库,因此我需要将其转换为PL / SQL函数。什么是等效的pl / sql函数?

预期结果应该是一行数据,列名为aCount,bCount,cCount,dCount(我已经完成了ADO.net代码并使用SQL Server存储过程)。这就是我到目前为止所拥有的。我知道的知识有限,我需要以某种方式使用光标,但无法弄清楚如何。

CREATE OR REPLACE FUNCTION some_proc(
    p_ix_sys_error OUT number
)
IS

    DECLARE 
        CountA NUMBER;
        CountB NUMBER;
        CountC NUMBER;
        CountD NUMBER;
    BEGIN
        SELECT COUNT(*) INTO CountA FROM some_table WHERE Status IN (7,8,9); 
        SELECT COUNT(*) INTO CountB FROM some_table WHERE Status IN (5);
        SELECT COUNT(*) INTO CountC FROM some_table WHERE Status IN (6);
        SELECT COUNT(*) INTO  CountD FROM some_table; 


    SELECT CountA AS aCount , CountB AS bCount , CountC AS cCount , CountD AS dCount

END

GO

1 个答案:

答案 0 :(得分:4)

最简单的翻译就像是

CREATE OR REPLACE FUNCTION some_proc(
    p_ix_sys_error OUT number,
    p_rc           OUT sys_refcursor
)
IS
    CountA NUMBER;
    CountB NUMBER;
    CountC NUMBER;
    CountD NUMBER;
BEGIN
    SELECT COUNT(*) INTO CountA FROM some_table WHERE Status IN (7,8,9); 
    SELECT COUNT(*) INTO CountB FROM some_table WHERE Status IN (5);
    SELECT COUNT(*) INTO CountC FROM some_table WHERE Status IN (6);
    SELECT COUNT(*) INTO  CountD FROM some_table; 

    OPEN p_rc
     FOR SELECT CountA AS aCount , 
                CountB AS bCount , 
                CountC AS cCount , 
                CountD AS dCount
           FROM dual;
END;

在任一系统上,对表执行单个查询而不是4个单独的查询

会更有效
CREATE OR REPLACE FUNCTION some_proc(
    p_ix_sys_error OUT number,
    p_rc           OUT sys_refcursor
)
IS
BEGIN
  OPEN p_rc
   FOR SELECT SUM( CASE WHEN Status IN (7,8,9)
                        THEN 1
                        ELSE 0
                    END ) aCount ,
              SUM( CASE WHEN Status IN (5)
                        THEN 1
                        ELSE 0
                    END ) bCount ,
              SUM( CASE WHEN Status IN (6)
                        THEN 1
                        ELSE 0
                    END ) cCount ,
              COUNT(*) dCount 
         FROM some_table;
END;

如果您只需要支持Oracle 12.1及更高版本,则可以打开隐式结果集,而不是声明单独的OUT参数,但我认为您也希望支持早期版本。