Conditional clause in the select statement

Hi all
Suppose for example of diagram of HR that I have the following query where it counts the number of Department based on their identity papers and the total number of jobs:
SQL> select decode(grouping(job_id),1,'total_job',job_id) as JobID, decode(group
ing(department_id),1,'all_department',department_id) as DepartmentID, count(*) f
rom employees group by rollup(job_id,department_id) order by job_id,department_i
d;

JOBID      DEPARTMENTID                               COUNT(*)
---------- ---------------------------------------- ----------
AC_ACCOUNT 110                                               1
AC_ACCOUNT all_department                                    1
AC_MGR     110                                               1
AC_MGR     all_department                                    1
AD_ASST    10                                                1
AD_ASST    all_department                                    1
AD_PRES    90                                                1
AD_PRES    all_department                                    1
AD_VP      90                                                2
AD_VP      all_department                                    2
FI_ACCOUNT 100                                               5

JOBID      DEPARTMENTID                               COUNT(*)
---------- ---------------------------------------- ----------
FI_ACCOUNT all_department                                    5
FI_MGR     100                                               1
FI_MGR     all_department                                    1
HR_REP     40                                                1
HR_REP     all_department                                    1
IT_PROG    60                                                5
IT_PROG    all_department                                    5
MK_MAN     20                                                1
MK_MAN     all_department                                    1
MK_REP     20                                                1
MK_REP     all_department                                    1

JOBID      DEPARTMENTID                               COUNT(*)
---------- ---------------------------------------- ----------
PR_REP     70                                                1
PR_REP     all_department                                    1
PU_CLERK   30                                                5
PU_CLERK   all_department                                    5
PU_MAN     30                                                1
PU_MAN     all_department                                    1
SA_MAN     80                                                5
SA_MAN     all_department                                    5
SA_REP     80                                               29
SA_REP                                                       1
SA_REP     all_department                                   30

JOBID      DEPARTMENTID                               COUNT(*)
---------- ---------------------------------------- ----------
SH_CLERK   50                                               20
SH_CLERK   all_department                                   20
ST_CLERK   50                                               20
ST_CLERK   all_department                                   20
ST_MAN     50                                                5
ST_MAN     all_department                                    5
total_job  all_department                                  107

40 rows selected.
The total number of global jobs regardless of which Department is 107. Question: How to make a query that displays the result above and makes the JOBID and DEPARTMENTID column value to two TotalAgregate where the count indicates 107? Like this:
JOBID      DEPARTMENTID                               COUNT(*)
---------- ---------------------------------------- ----------
AC_ACCOUNT 110                                               1
AC_ACCOUNT all_department                                    1
AC_MGR     110                                               1
AC_MGR     all_department                                    1
AD_ASST    10                                                1
AD_ASST    all_department                                    1
AD_PRES    90                                                1
AD_PRES    all_department                                    1
AD_VP      90                                                2
AD_VP      all_department                                    2
FI_ACCOUNT 100                                               5

JOBID      DEPARTMENTID                               COUNT(*)
---------- ---------------------------------------- ----------
FI_ACCOUNT all_department                                    5
FI_MGR     100                                               1
FI_MGR     all_department                                    1
HR_REP     40                                                1
HR_REP     all_department                                    1
IT_PROG    60                                                5
IT_PROG    all_department                                    5
MK_MAN     20                                                1
MK_MAN     all_department                                    1
MK_REP     20                                                1
MK_REP     all_department                                    1

JOBID      DEPARTMENTID                               COUNT(*)
---------- ---------------------------------------- ----------
PR_REP     70                                                1
PR_REP     all_department                                    1
PU_CLERK   30                                                5
PU_CLERK   all_department                                    5
PU_MAN     30                                                1
PU_MAN     all_department                                    1
SA_MAN     80                                                5
SA_MAN     all_department                                    5
SA_REP     80                                               29
SA_REP                                                       1
SA_REP     all_department                                   30

JOBID      DEPARTMENTID                               COUNT(*)
---------- ---------------------------------------- ----------
SH_CLERK   50                                               20
SH_CLERK   all_department                                   20
ST_CLERK   50                                               20
ST_CLERK   all_department                                   20
ST_MAN     50                                                5
ST_MAN     all_department                                    5
TotalAgregate  TotalAgregate                                107

40 rows selected.
Best regards
Valerie

I do not have the HR schema to play with, but isn't it just a nested decode it takes?

for example something like...

select decode(grouping(job_id),1,'TotalAggregate',job_id) as JobID
      ,decode(grouping(department_id),1,decode(grouping(job_id),1,'TotalAggregate','all_department'),department_id) as DepartmentID
      ,count(*)
from employees
group by rollup(job_id,department_id)
order by job_id,department_id;

Tags: Database

Similar Questions

  • How to split string separated by commas and pass to the clause of the select statement

    Referring to article How to divide string separated by commas, then pass to clause of a select statement, tquery that there the following plan:

    Query1:

    select * from emp where ename in (
        select regexp_substr('SMITH,ALLEN,WARD,JONES','[^,]+', 1, level) from dual
        connect by regexp_substr('SMITH,ALLEN,WARD,JONES', '[^,]+', 1, level) is not null );
    

    Base1:

    Plan hash value: 4242290184
    
    
    --------------------------------------------------------------------------------------------
    | Id  | Operation                       | Name     | Rows  | Bytes | Cost (%CPU)| Time     |
    --------------------------------------------------------------------------------------------
    |   0 | SELECT STATEMENT                |          |     1 |   133 |     7  (29)| 00:00:01 |
    |*  1 |  HASH JOIN                      |          |     1 |   133 |     7  (29)| 00:00:01 |
    |   2 |   VIEW                          | VW_NSO_1 |     1 |    46 |     3  (34)| 00:00:01 |
    |   3 |    HASH UNIQUE                  |          |     1 |       |     3  (34)| 00:00:01 |
    |*  4 |     CONNECT BY WITHOUT FILTERING|          |       |       |            |          |
    |   5 |      FAST DUAL                  |          |     1 |       |     2   (0)| 00:00:01 |
    |   6 |   TABLE ACCESS FULL             | EMP      |    14 |  1218 |     3   (0)| 00:00:01 |
    --------------------------------------------------------------------------------------------
    
    
    Predicate Information (identified by operation id):
    ---------------------------------------------------
    
    
       1 - access("ENAME"="$nso_col_1")
       4 - filter( REGEXP_SUBSTR ('SMITH,ALLEN,WARD,JONES','[^,]+',1,LEVEL) IS NOT NULL)
    

    However, the following query generates the plan I want:

    Query2:

    select * from emp where ename in ('SMITH','ALLEN','WARD','JONES');
    

    Plan2:

    Plan hash value: 3956160932
    
    
    --------------------------------------------------------------------------
    | Id  | Operation         | Name | Rows  | Bytes | Cost (%CPU)| Time     |
    --------------------------------------------------------------------------
    |   0 | SELECT STATEMENT  |      |     4 |   348 |     3   (0)| 00:00:01 |
    |*  1 |  TABLE ACCESS FULL| EMP  |     4 |   348 |     3   (0)| 00:00:01 |
    --------------------------------------------------------------------------
    
    
    Predicate Information (identified by operation id):
    ---------------------------------------------------
    
    
       1 - filter("ENAME"='ALLEN' OR "ENAME"='JONES' OR "ENAME"='SMITH' OR
                  "ENAME"='WARD')
    

    Can I change the query1 query for plan2?

    As Juliet was mentioned in the first SQL that you generate from the ENAME list that you must pass in the IN clause when executing. But in the second SQL, it passed as a static value. So first SQL must do more work. So you see a different execution plan.

    But this is a work around to get what you are looking for. But I can't say it's a foolproof method. But anyway here you go.

    SQL > var ename_list varchar2 (100)
    SQL > exec: ename_list: = 'SMITH, ALLEN, WARD, JONES ';

    PL/SQL procedure successfully completed.

    SQL > select *.
    2 of PEM
    where the 3 «,» | : ename_list | ',' like '%', | Ename | ',%';

    EMPNO, ENAME, JOB HIREDATE DEPTNO ID COM SAL MGR
    ---------- ------ --------- ---------- --------- ---------- ---------- ---------- ----------
    7369 SMITH COMMITTED 7902 2975 2 APRIL 81 0 20
    7499 ALLEN 7698 1600 20 FEBRUARY SALESMAN 81 300 30
    7521 WARD 7698 1250 22 FEBRUARY SALESMAN 81 500 30
    7566 JONES MANAGER 7839 2975 2 APRIL 81 0 20

    SQL > select * from table (dbms_xplan.display_cursor);

    PLAN_TABLE_OUTPUT
    -------------------------------------------------------------------------------------------------------
    SQL_ID, 848zhvbvgf7d6, number of children 0
    -------------------------------------
    Select * from emp where «,» | : ename_list | ',' like '%', | Ename
    || ',%'

    Hash value of plan: 2872589290

    --------------------------------------------------------------------------
    | ID | Operation | Name | Lines | Bytes | Cost (% CPU). Time |
    --------------------------------------------------------------------------
    |   0 | SELECT STATEMENT |      |       |       |     2 (100) |          |
    |*  1 |  TABLE ACCESS FULL | EMP |     1.    38.     2 (0) | 00:00:01 |
    --------------------------------------------------------------------------

    Information of predicates (identified by the operation identity card):
    ---------------------------------------------------

    1 - filter(','||:ENAME_LIST||',' LIKE '%,'||") ENAME "|", %')

    19 selected lines.

    SQL >

  • Using arrary associative as parameter and passing then to the place where the clause of the select statement

    Hello

    I have this scenario where I have to pass multiple values to a parameter of a procedure of monkey and then collect in another variable (the lines can be multiple).

    The parameter must be used in the where clause of the statement select here I create a sample table for the problem.

    Create table test_tab (number of trans_id, cmts varchar2 (50));

    insert into test_tab values (568890112115, ' wnlb-CMTS-11-04' ");

    insert into test_tab values (568890112115, ' wnlb-CMTS-11-04' ");

    insert into test_tab values (568890112115, ' wnlb-CMTS-11-01' ");

    insert into test_tab values (568890112115, ' wnlb-CMTS-11-01' ");

    insert into test_tab values (568890112115, ' wnlb-CMTS-11-01' ");

    insert into test_tab values (568890112115, ' wnlb-CMTS-12-02' ");

    insert into test_tab values (568890112115, ' wnlb-CMTS-12-02' ");

    This is so all cmts have same trans_id but different name

    This query gives the result as -

    Select the cmts, count (1)

    of test_tab

    where cmts ("wnlb-cmts-11-04','wnlb-cmts-11-01", "wnlb-CMTS-11-02'")

    and trans_id = 568890112115

    Cmts group;

    COUNTY OF CMTS

    WNLB-CMTS-11-04 2

    3 WNLB-CMTS-11-01

    Now, I want to use this query in a PLSQL block like where I can spend the CMTS collection and trans_id as a scalar variable and once again an OUTPUT parameter that holds the result of the query.

    I use OUT parameter because it will be called to the JAVA program.

    Here, I write a PACKAGE for it but it gives me compilation error!

    create or replace package CMTS_SUCCESS_FAILED_API

    is

    type t_item_name is table of index varchar2 (50) by pls_integer;

    TYPE t_cmts_count () IS RENDERING

    CMTS VARCHAR2 (30),

    number of NUMBER

    );

    type t_reseg_dtl is table of index t_cmts_count by pls_integer;

    procedure CMTS_SUCCESS_FAILED_RESEG_ORDR (p_item_name t_item_name, p_trans_id in numbers, p_reseg_dtl to t_reseg_dtl);

    end CMTS_SUCCESS_FAILED_API;

    /

    Now that I have created a different PACKAGE BODY, but none don't work!

    1.

    create or replace package CMTS_SUCCESS_FAILED_API

    is

    type t_item_name is table of index varchar2 (50) by pls_integer;

    TYPE t_cmts_count () IS RENDERING

    CMTS VARCHAR2 (30),

    number of NUMBER

    );

    type t_reseg_dtl is table of index t_cmts_count by pls_integer;

    procedure CMTS_SUCCESS_FAILED_RESEG_ORDR (p_item_name t_item_name, p_trans_id in numbers, p_reseg_dtl to t_reseg_dtl);

    end;

    /

    create or replace package CMTS_SUCCESS_FAILED_API body

    is

    procedure CMTS_SUCCESS_FAILED_RESEG_ORDR (p_item_name t_item_name, p_trans_id in numbers, p_reseg_dtl to t_reseg_dtl)

    is

    Start

    I'm in p_item_name.first... p_item_name. Last

    loop

    Select the cmts, count (1)

    bulk collect into p_reseg_dtl (i)

    of test_tab

    where cmts = p_item_name (i)

    and trans_id = p_trans_id

    Cmts group;

    end loop;

    for r in p_reseg_dtl.first... p_reseg_dtl. Last

    loop

    dbms_output.put_line (p_reseg_dtl (r). TRANSACTION_ID | » '|| p_reseg_dtl (r). JOB_STATUS | » '|| p_reseg_dtl (r). CMTS);

    end loop;

    end CMTS_SUCCESS_FAILED_RESEG_ORDR;

    end CMTS_SUCCESS_FAILED_API;

    While I run this procedure it is said TOO_MANY LINES.

    2.

    create or replace package CMTS_SUCCESS_FAILED_API body

    is

    procedure CMTS_SUCCESS_FAILED_RESEG_ORDR (p_item_name t_item_name, p_trans_id in numbers, p_reseg_dtl to t_reseg_dtl)

    is

    cursor c_dtl is

    Select the cmts, count (1)

    of test_tab

    where cmts = p_item_name < < error

    and trans_id = p_trans_id

    Cmts group;

    Start

    Open c_dtl;

    collect the fetch c_dtl in bulk in p_reseg_dtl;

    close c_dtl;

    -for i in p_item_name.first... p_item_name. Last

    -loop

    -end loop;

    end;

    end;

    THIS error GIVES BODY as EXPRESSION IS OF TYPE INCORRECT for where clause where I mark it as "BOLD".

    I think Miss me a small detail to add here, but I can't do even now it seems for me that I'm working on it since the morning and SQL are a little complex in real time who also write.


    I use-

    Oracle Database 11 g Enterprise Edition Release 11.2.0.1.0 - 64 bit Production

    Please suggest me!

    Until then I'm also working on this issue hope will find a solution.

    In the database (we show it with a standalone function, you should put it in a package):

    create or replace function CMTS_SUCCESS_FAILED_RESEG_ORDR (
      p_item_name IN SYS.DBMS_DEBUG_VC2COLL,
      p_trans_id IN number
    )
    return sys_refcursor is
      l_refcur sys_refcursor;
    begin
      open l_refcur for
        SELECT cmts , COUNT(*)
          FROM test_tab
        WHERE cmts member of p_item_name
           AND trans_id = p_trans_id
        GROUP BY cmts;
      return l_refcur;
    end CMTS_SUCCESS_FAILED_RESEG_ORDR;
    /
    

    In Java:

    import java.math.BigDecimal;
    import java.sql.CallableStatement;
    import java.sql.Connection;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    
    import oracle.jdbc.OracleCallableStatement;
    import oracle.jdbc.OracleTypes;
    import oracle.jdbc.pool.OracleDataSource;
    import oracle.sql.ARRAY;
    import oracle.sql.ArrayDescriptor;
    
    public class SQLCollection {
    
        public static void main(String[] args) throws SQLException {
    
            System.out.println("Class SQLCollection started.");
    
            OracleDataSource ods = null;
            Connection conn = null;
            CallableStatement cs = null;
            ResultSet rset = null;
    
            try {
                ods = new OracleDataSource();
                String url = "jdbc:oracle:thin:@//127.0.0.1:1522/orcl.localdomain";
                ods.setURL(url);
                ods.setUser("stew");
                ods.setPassword("stew");
                conn = ods.getConnection();
                conn.setAutoCommit(false);
    
                ArrayDescriptor oracleVarchar2Collection =
                    ArrayDescriptor.createDescriptor("SYS.DBMS_DEBUG_VC2COLL", conn);
                String[] inset = new String[2];
                inset[0] = "wnlb-cmts-11-04";
                inset[1] = "wnlb-cmts-11-01";
                ARRAY ora_inset = new ARRAY(oracleVarchar2Collection, conn, inset);
    
                cs = conn.prepareCall("begin ? := CMTS_SUCCESS_FAILED_RESEG_ORDR(?, ?); end;");
                cs.registerOutParameter(1, OracleTypes.CURSOR);
                cs.setArray(2, ora_inset);
                cs.setBigDecimal(3, new BigDecimal("568890112115"));
                cs.execute();
    
                // Dump the cursor
                rset = ((OracleCallableStatement)cs).getCursor(1);
                while (rset.next())
                    System.out.println(rset.getString(1) + ": " + rset.getInt(2));
    
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (rset != null) {
                    rset.close();
                }
                if (cs != null) {
                    cs.close();
                }
                if (conn != null) {
                    conn.close();
                }
                System.out.println("Class SQLCollection ended.");
            }
        }
    }
    
  • Using the conditional to determine the Select statement

    I don't know if anyone knows if I can do that, but I try to use a factor based on a value on what query to run...

    Something like:
    DECODE('INBOUND', 
         'INBOUND', SELECT 'I' FROM DUAL, 
         'OUTBOUND', SELECT 'O' FROM DUAL, 
         'BOTH', SELECT 'B' FROM DUAL);
    OR
    SELECT * 
          FROM 
          ( 
               CASE 
                    WHEN '<~S~>' = 'INBOUND' THEN SELECT 'INBOUND' FROM DUAL 
                    WHEN '<~S~>' = 'OUTBOUND' THEN SELECT 'OUTBOUND' FROM DUAL 
                    ELSE SELECT 'BOTH' FROM DUAL 
               END 
           ) AllValues
    Is it still possible?

    Thank you
    Andy

    Published by: 847975 on September 28, 2011 11:02

    Scalar subqueries should appear in square brackets, for example

    select case dummy
              when 'X' then (select 'First example' from dual)
              when 'Y' then (select 'Second example' from dual)
           end as demo
    from dual;
    

    or if you prefer the old syntax DECODE,

    select decode(dummy,
                  'X', (select 'First example' from dual),
                  'Y', (select 'Second example' from dual)
           ) as demo
    from dual;
    
  • an INTO clause in this SELECT statement

    Hello

    This query is to start an error, an INTO clause in the SELECT statement. I have a line in my table

    DECLARE

    TNom VARCHAR (100);

    BEGIN

    Select tNom under Tnom in t_conf where Tna = 'Home';

    If instr (tNom, 'living room') > 0

    then return true;

    otherwise return false;

    end if;

    END;

    DECLARE

    v_Tname VARCHAR (100);

    BEGIN

    Select Tname in v_Tname t_conf where Tna = 'Home';

    If instr (v_Tname, "living room") > 0

    then return true;

    otherwise return false;

    end if;

    END;

  • function() nested in the select statement

    Oracle 11g. Try to nest a function within the select statement.  Goal: get the average customer rating for each of the qualified user.

    Select user_name, f_get_avg_cust_rating() "Notation.

    of u, OTHER_TABLES o TAB_USER

    where u.id = o.id and another condition matched;

    How Oracle would deal with the sql.  Is it

    (1) first of all display records based on the where clause, then call the f_get_avg_cust_rating() for each of the selected records OR

    (2) for the analysis in tables, the f_get_avg_cust_rating() will be called for each record met?

    Thank you

    Scott

    Words of Frank, I created two functions with dbms_output and used a function in where clause in select another function. See the bottom of the unit tests. Everyone says, where first clause then select...

    -Where function clause

    SQL > CREATE or REPLACE FUNCTION ret_empno

    2 RETURN NUMBER

    3 AS

    4 BEGIN

    5 DBMS_OUTPUT. Put_line (' where Clause Function');

    6 RETURN 7839;

    7 END;

    8.

    The function is created.

    -Select the function

    SQL > CREATE or REPLACE FUNCTION ret_1

    2 RETURN NUMBER

    3 AS

    4 BEGIN

    5 DBMS_OUTPUT. Put_line ('Select function');

    6 RETURN 1;

    7 END;

    8.

    The function is created.

    SQL > SELECT empno, ename,ret_1

    2 FROM emp

    3. WHERE empno = ret_empno;

    EMPNO, ENAME RET_1

    ---------- ---------- ----------

    7839 KING 1

    Where the function Clause

    Select the function

  • command evaluated Pivot and UnPivot in the select statement

    My research assessing the order of the select statement is below.
     1 from
     2 where (Join condition)
     3 start with
     4 connect by
     5 where (filter of rows)
     6 group by
     7 having
     8 model
     9 select
    10 order by
    My question is Where clause Pivot and UnPivot clause ?

    http://download.Oracle.com/docs/CD/E16338_01/server.112/e10592/statements_10002.htm

    Well the pivot is applied to a single table or an inline or a view - so it's going to be like any other table or view in the list - it will be first

    select b.BUSINESS_OBJECT_CATEGORY_DESCR, a.c, a.d
    from
     (select PAY_METHOD_TYPE_CODE, BUSINESS_OBJECT_CATEGORY_CODE
      from target_odi.business_object_pay_methods)
     pivot (count(PAY_METHOD_TYPE_CODE)
             for PAY_METHOD_TYPE_CODE in  ('D' as d, 'C' as c)) a ,
    target_odi.business_object_categories  b
    where a.BUSINESS_OBJECT_CATEGORY_CODE = b.BUSINESS_OBJECT_CATEGORY_CODE
    

    So for the SQL above the pivot is first assessed before the join between A and B.

  • uniol all in the select statement

    Hi I have a situation where I have to return the value based on the if statement, is it possible to put union all in the select statement

    My use case is

    IN the column State

    If column01 > 0 to condtion 't'

    IF column02 > 0 that the condition of 'Y '.

    Condition IF COLUMN03 > 0 THAN 'w '.

    If COLUMN04 > 0 that the condition of "Z".

    Select 't'

    TableName

    where column01 > 0

    Union of all the

    Select "y".

    TableName

    where column02 > 0

    Union of all the

    Select 'W '.

    TABLENAME

    WHERE COLUMN03 > 0

    I have what it takes to show value as it

    EmpName, condition, empno

    Jerry, T, 0158754585

    TOM, Y, 0054789568

    Am in oracle database 11 g 2

    Yes you can put all THE UNION here

    Select empname, 't' State, empno from tablename where column01 > 0

    Union of all the

    Select empname, 't' State, empno from tablename where column02 > 0

    Union of all the

    Select empname, condition of "W", empno FROM tablename WHERE COLUMN03 > 0

    Union of all the

    Select empname, condition of "Z", empno FROM tablename WHERE COLUMN04 > 0

    and if you are looking for how to remove duplicates because your line might have satisfied all the conditions and my happen 4 times in your result set, you just need to give them an order and filter it.

    For example, you want this

    If column01 > 0 to condtion 't'

    ELSE IF column02 > 0 that the condition of 'Y '.

    Another condition of THAN > 0 IF COLUMN03 'w '.

    otherwise if COLUMN04 > 0 that the condition of "Z".

    Select empname, condition, empno, in

    (

    Select a.*, row_number() over (partition by empno arrested by myorder) rn

    Of

    (

    Select empname, 't' State, empno, 1 myorder tablename where column01 > 0

    Union of all the

    Select empname, 't' State, empno, 2 myorder tablename where column02 > 0

    Union of all the

    Select empname, condition of "W", empno 3 myorder FROM tablename WHERE COLUMN03 > 0

    Union of all the

    Select empname, empno, condition of 'Z', 4 myorder FROM tablename WHERE COLUMN04 > 0

    ) a

    ) where rn = 1

  • Error PLS-00428: an INTO clause in this SELECT statement

    Dear Experts,

    I'm new to PL/SQL programming

    I try to run the following query, I get the error message.

    Please help me solve the error.

    declare

    var_cd number (20);

    Start

    If: P1_TYP_CAT is not null then

    SELECT max (CAT_cd + 1) as var_cd from IM_AST_CAT by CAT_cd;

    insert into IM_AST_CAT (CAT_NM, CAT_CD) values ((upper (:P1_TYP_CAT)),(:var_cd));

    on the other

    RAISE_APPLICATION_ERROR ('-20001,' both Department and location must be provided ");

    end if;

    end;

    In PL/SQL, must be used IN the clause when using SELECT statements.

    SELECT max (CAT_cd + 1) as var_cd

    in variable - it is missing in your code

    from IM_AST_CAT by CAT_cd;

    Your code should be

    declare

    var_cd number (20);

    Start

    If: P1_TYP_CAT is not null then

    SELECT max (CAT_cd + 1).
        in var_cd
    of IM_AST_CAT
    order of CAT_cd;

    insert into IM_AST_CAT (CAT_NM, CAT_CD) values (upper(:P1_TYP_CAT), var_cd);

    on the other

    RAISE_APPLICATION_ERROR ('-20001,' both Department and location must be provided ");

    end if;

    end;

    For example:

    DECLARE

    l_first_name varchar2 (100);

    BEGIN

    Select first_name

    in l_first_name

    employees

    where employee_id = 100;

    END;

    Post edited by: Suri

  • How to use the variable instead of the table name in the select statement of procedure

    I have a procedure with a select statement with dynamic from clause. How can I use instead of the name of the table variable.

    create or replace procedure scc_chemical_analysis
    is
    v_table_name varchar2 (100);
    Start

    declare
    cursor c1 is select * from v_table_name; -This is the variable name. How can I use it in the select statement.
    .
    .
    .
    .



    end;

    Hello

    something like that.

      1  declare
      2     vSQLString      VARCHAR2(32000);
      3  pTableName varchar2(1000):='EMP';
      4  BEGIN
      5     vSQLSTRING :=
      6  'SELECT ''x'' FROM ' || DBMS_ASSERT.sql_object_name(pTableName) || ' WHERE rownum<=1 ';
      7     EXECUTE IMMEDIATE vSQLSTRING;
      8* END;
    SQL> /
    
    PL/SQL procedure successfully completed.
    
  • MV without ROWID specified in the select statement

    Hello

    Can we create a ROWID specified in the statement select the DDL with out MV when we create a MV with 2 tables join.
    It comes to my requirement but, apparently, this is not possible. Are there opportunities to achieve.

    Thank you
    Pramod

    Pramod Garre wrote:
    Can we create a MV that can be updated FAST with the ROWID specified in the select statement in the DDL when we create a MV with 2 tables join.

    As mentioned previous you are best to check the documentation. Here is an excerpt from the documentation on this topic (emphasis added):

    Limitation to fast refresh materialized views with joins only

    Definition of materialized views with joints only and no aggregate queries have the following restrictions on fast refresh:

    * All 'General Restrictions on Fast Refresh' restrictions.
    * They cannot have aggregate or GROUP BY clauses.
    * The ROWID of all tables in the list must appear in the SELECT list of the query.*
    >

    For example, if the problem is that when you describe the view you have ROWID and you don't want them there, then I suggest to implement a regular vision on top of the materialized view that hides these columns.

    HTH!

  • call a function in a where clause of a select statement clause

    Hello

    is it possible to call a function in a where clause of a select statement clause?

    ex: select col1, col2
    from my_table
    where my_package.my_function (32199, 2008, col3, 'P');

    and I have the error message ' ORA-00920: invalid relational operator.

    FUNCTION ma_fonction (v_matricule in NUMBER,
    v_Year in NUMBERS
    T_DATE IN a DATE,
    v_type in DEFAULT CHAR 'P')
    RETURN A BOOLEAN VALUE;

    @+ Rosagio

    Yes, it is possible.

    But you have no relational operator:

    where my_package.my_function (32199, 2008, col3, 'P') =?
    where my_package.my_function (32199, 2008, col3, 'P') >?
    where my_package.my_function (32199, 2008, col3, 'P')<>

    Oops, I just noticed that your function returns a Boolean value.

    Can't do that as in a SQL statement.

    Boolean is known only to other code PL/SQL, no SQL statements.

    Published by: SomeoneElse on November 7, 2008 09:24

  • mixture of column type in the select statement

    Oracle 11g r2.

    tab_test (name varchar2, blob... photo)

    (1) select general use *.

    Stored procedure: open ref_cursor to some * of table_test...

    Coast of java: call.registerOutParameter (1, OracleTypes.CURSOR);  Call.Execute ();

    It works very well.

    (2) enter the name of the column in the select such as

    Stored procedure: open ref_cursor to select name, photo table_test...

    Coast of java: call.registerOutParameter (1, OracleTypes.CURSOR);  Call.Execute ();

    ERROR: java.sql.SQLSyntaxErrorException: ORA-00932: inconsistent data types: expected - got BLOB

    My question, if I specify the column names in the select statement, including the varchar2 and blob, how can I registerOutParameter (1, OracleTypes.CURSOR);?

    Thank you

    Scott

    PS The number of returned columns, in real case schenario, is a little, so I prefer to specify column names.

    Wrong forum. This forum is for questions of sql and pl/sql.

    Enter the question ANSWER and the repost in the JDBC forum

    https://community.oracle.com/community/developer/english/java/database_connectivity/java_database_connectivity _(jdbc)

    When repost you provide the necessary information to help you:

    1. information on the full version for Oracle DB

    2 version of the JDK

    3. the name and version of the JDBC jar file

    4. real code that demonstrates the problem

    You should also review the info re REF CURSOR in the JDBC Developer's Guide

    http://docs.Oracle.com/CD/E16655_01/Java.121/e17657/oraint.htm#i1058743

  • Pivot will not get result in the select statement

    This is the version of oracle 11g R2 on windows details 7 OS

    CREATE TABLE OTBOOKINGDETAILS
    (EMPNO VARCHAR2 (10 BYTE),
    DATE OF OTBOOKEDDATE,
    NUMBER (5.0) DAY OF THE WEEK.
    DAYCEILINGHRS VARCHAR2 (10 BYTE));

    Here is the data

    INSERT INTO OTBOOKINGDETAILS VALUES (101 ', 3 MARCH 2013', 1,' 09:00 ');
    INSERT INTO OTBOOKINGDETAILS VALUES (101 ', 3 APRIL 2013', 2' 01:00 ');
    INSERT INTO OTBOOKINGDETAILS VALUES (101 ', 3 MAY 2013', 3,' 01:00 ');
    INSERT INTO OTBOOKINGDETAILS VALUES (101 ', 3 JUNE 2013', 4' 01:00 ');
    INSERT INTO OTBOOKINGDETAILS VALUES (101 ', 3 JULY 2013', 5,' 01:00 ');
    INSERT INTO OTBOOKINGDETAILS VALUES (101 ', 3 AUGUST 2013', 6,' 01:00 ');
    INSERT INTO OTBOOKINGDETAILS VALUES (101 ', 3 SEPTEMBER 2013', 7,' 00:00 ');
    INSERT INTO OTBOOKINGDETAILS VALUES (102 ', 3 MARCH 2013', 1,' 09:00 ');
    INSERT INTO OTBOOKINGDETAILS VALUES (102 ', 3 APRIL 2013', 2' 01:00 ');
    INSERT INTO OTBOOKINGDETAILS VALUES (102 ', 3 MAY 2013', 3,' 01:00 ');
    INSERT INTO OTBOOKINGDETAILS VALUES (102 ', 3 JUNE 2013', 4,' 02:00 ');
    INSERT INTO OTBOOKINGDETAILS VALUES (102 ', 3 JULY 2013', 5,' 01:00 ');
    INSERT INTO OTBOOKINGDETAILS VALUES (102 ', 3 AUGUST 2013', 6,' 04:00 ');
    INSERT INTO OTBOOKINGDETAILS VALUES (102 ', 3 SEPTEMBER 2013', 7' 01:00 ');
    INSERT INTO OTBOOKINGDETAILS VALUES (101 ', 3 OCTOBER 2013', 1,' 00:00 ');
    INSERT INTO OTBOOKINGDETAILS VALUES (101 ', 3 NOVEMBER 2013', 2' 01:00 ');
    INSERT INTO OTBOOKINGDETAILS VALUES (101 ', 3 DECEMBER 2013', 3,' 01:00 ');
    INSERT INTO OTBOOKINGDETAILS VALUES (101 ', 13 MARCH 2013', 4,' 04:45 ');
    INSERT INTO OTBOOKINGDETAILS VALUES (101 ', 14 MARCH 2013', 5,' 01:00 ');
    INSERT INTO OTBOOKINGDETAILS VALUES (101 ', 15 MARCH 2013', 6,' 01:00 ');
    INSERT INTO OTBOOKINGDETAILS VALUES (101 ', 16 MARCH 2013', 7' 01:00 ');

    Here, I want to Dayceiling hours below the output using pivot

    EMPNO OTBOOKEDDATE DAY1_HRS DAY2_HRS DAY3_HRS DAY4_HRS DAY5_HRS DAY6_HRS DAY7_HRS
    101 03/03/2013 09:00 01:00 01:00 01:00 01:00 01:00 00:00
    102 03/03/2013 09:00 01:00 01:00 02:00 01:00 04:00 01:00
    101 03/10/2013 00:00 01:00 01:00 04:45 01:00 01:00 01:00

    ChakravarthyDBA wrote:
    I need to include the pivot query in the select statement

    Can' are you use PIVOT here since you do not know from the start what values OTBOOKEDDATE. So use:

    select  empno,
            otbookeddate - weekday + 1 otbookeddate,
            max(
                case weekday
                  when 1 then dayceilinghrs
                end
               ) day1_hrs,
            max(
                case weekday
                  when 2 then dayceilinghrs
                end
               ) day2_hrs,
            max(
                case weekday
                  when 3 then dayceilinghrs
                end
               ) day3_hrs,
            max(
                case weekday
                  when 4 then dayceilinghrs
                end
               ) day4_hrs,
            max(
                case weekday
                  when 5 then dayceilinghrs
                end
               ) day5_hrs,
            max(
                case weekday
                  when 6 then dayceilinghrs
                end
               ) day6_hrs,
            max(
                case weekday
                  when 7 then dayceilinghrs
                end
               ) day7_hrs
      from  otbookingdetails
      group by empno,
               otbookeddate - weekday + 1
      order by otbookeddate,
               empno
    /
    
    EMPNO      OTBOOKEDDA DAY1_HRS   DAY2_HRS   DAY3_HRS   DAY4_HRS   DAY5_HRS   DAY6_HRS   DAY7_HRS
    ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ----------
    101        03-03-2013 09:00      01:00      01:00      01:00      01:00      01:00      00:00
    102        03-03-2013 09:00      01:00      01:00      02:00      01:00      04:00      01:00
    101        10-03-2013 00:00      01:00      01:00      04:45      01:00      01:00      01:00
    
    SQL> 
    

    SY.

  • validation for each 1,000 records to be inserted in the select statement

    Hi, I have the following INSERTION in the SELECT statement.
    The SELECT statement (who joined) data fo about 6 crores. I need to insert this data into another table.

    Please suggest me the best way to do it.
    I use the INSERT in the SELECT statement, but I want to use the statement commit for each 1,000 records.

    How can I do this...
    insert into emp_dept_master 
     select e.ename ,d.dname ,e.empno ,e.empno ,e.sal 
       from emp e , dept d
      where e.deptno = d.deptno       ------ how to use commit for every 1000 records .
    Thank you

    Method 4 is the best

    You could combine method 3 and 1 (without dynamic SQL)

    Method 2 is the less optimal solution from the list.

Maybe you are looking for