Different selection in a single query according to an ID

Hi
I'm looking for a way to perform different selections in a single query according to a specific value:
Here is the first selection:
  select g.*,gf.*,gs.*         
  FROM graphs g
  LEFT JOIN graph_frames gf on g.graph_id = gf.graph_id
  LEFT JOIN graph_sets gs on gf.frame_id = gs.frame_id
  WHERE g.graph_id = :IDHere is the second selection:
  SELECT gg.graph_id, gg.graph_name
  FROM generic_graphs gg
  INNER JOIN generic_graph_frames ggf on gg.graph_id = ggf.graph_id
  INNER JOIN generic_graph_sets ggs on ggf.frame_id = ggs.frame_id
  WHERE gg.graph_id = :IDNow, the ID cannot be in both the tables and I want to perform that in a single query, UNION cannot be applied since the tables are different.
Any ideas?
Edited by: BluShadow on 14-Sep-2011 09:09
added {noformat}{noformat} tags.  Please read {message:id=9360002} and learn to do this yourself.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

Example of consolidating the columns...
SQL> ed
Wrote file afiedt.buf
  1  with t as (select &id as id from dual)
  2  select e.empno, e.ename, e.job, e.mgr, d.deptno, d.dname, d.loc
  3  from   (select * from emp cross join t where empno = t.id) e
  4         full outer join
  5         (select * from dept cross join t where deptno = t.id) d
  6*        on (1=1)
SQL> /
Enter value for id: 7521
old   1: with t as (select &id as id from dual)
new   1: with t as (select 7521 as id from dual)
     EMPNO ENAME      JOB              MGR     DEPTNO DNAME          LOC
      7521 WARD       SALESMAN        7698
SQL> /
Enter value for id: 10
old   1: with t as (select &id as id from dual)
new   1: with t as (select 10 as id from dual)
     EMPNO ENAME      JOB              MGR     DEPTNO DNAME          LOC
                                                   10 ACCOUNTING     NEW YORK
SQL>Though, this would be considered poor design because you are trying to query two disperate things, so they should be treated differently. i.e. in my example, I should already know if I'm querying an employee or a department beforehand.

Similar Messages

  • Is it possible to combine 2 different reports in a single Query?

    Dear All,
    What am I working at?
    I produced a Query for Debtors Aged Analysis which mimics the Official SAP B1 8.8 Aging Report.
    It ages the outstanding invoices by Posting Date ( RefDate  in JDT1)
    I also made another Report which ages outstanding amounts by Document Date simply by replacing all RefDate by TaxDate
    They give different answers if Posting Date is different from Document Date, e.g a manual invoice dated 5 Jun 2011 is posted on 2 Jul 2011.
    What I want to do?
    My idea is to produce a SINGLE QUERY which will generate either Aging depending on settings:
        (a) A Debtors Aging by Posting Date
        (b) A Debtors Aging by Document Date
    I declare 2 variables:
    (a) @refdt  is [%1] and represents Posting Date (JDT1 RefDate)
    (b) @taxdt  is [%2] and represents Document Date (JDT1 TaxDate)
    When the Query is run, the foll dialog appears:
    Query - Selection Criteria
    Posting Date             Equal .......
    Document Date            Equal .......
    OK   Cancel
    We are expected to fill in only 1 date and leave the other blank, and Query will generate the required report .
    What is my problem?
    Query runs smoothly, but amounts in the Balance column does not get analyzed in the Age brackets: Current / 1 Mth Ago / etc
    I think I know where's the problem
    I am assuming (wrongly) that if we don't fill one date field, the query returns NULL for that variable. In fact, it appears to return GetDate().
    Help
    Can anybody help me put the correct commands so that all my balances are correctly analysed in the respective age buckets?
    Thanks
    Leon Lai
    Here's a simplified SQL:
    Tables  :
          JDT1   T0  = Journal Entry - Rows
          OCRD T1 = Business Partner
          OCPR T2 = Contact Person
          OJDT  T3  = Journal Entry - Header
          OINV   T4  = A/R Invoices - Header
          ORIN   T5  - A/R Credit Memo - Header
    declare @refdt date
    declare @taxdt date
    set @refdt
    /*Select 1 from jdt1 t where t.RefDate*/ = [%1]
    set @taxdt
    /*Select 1 from jdt1 w where w.TaxDate*/ = [%2]
    SELECT
    'company1' AS 'Company',
    T1.CardCode  AS 'BP Code',
    T2.Notes2 AS 'BP Name',
    T0.RefDate AS 'Pstg Dt',
    T0.TaxDate AS 'Doc Dt',
    CASE
             WHEN T0.TransType = 13 THEN 'IN'
             WHEN T0.TransType = 14 THEN 'CN'
             WHEN T0.TransType = 30 THEN 'JE'
             WHEN T0.TransType = 24 THEN 'RC'
             WHEN T0.TransType = 46 THEN 'PS'
             ELSE 'Error ! ! !'
    END AS 'Doc Type',
    T0.Ref1 'Doc. Number',
    ISNULL(T0.FCCurrency, ' - ') AS 'Ccy',
    (T0.FCDebit - T0.FCCredit) AS 'Orig. F.Ccy',
    (T0.BalFcDeb - T0.BalFcCred) AS 'Bal. F. Ccy',
    (T0.Debit - T0.Credit) AS 'Orig. Rs',
    (T0.BalDueDeb - T0.BalDueCred) AS 'Bal. Rs',
    /* ########################  PROBLEM is here   ################## */
    CASE
                   WHEN (@refdt is not null) and (@taxdt is null)
                   THEN ISNULL((SELECT T0.BalDueDeb -T0.BalDueCred
                   WHERE DateDiff(mm, T0.RefDate, @refdt) = 0 ) ,0)
                   WHEN (@refdt is null) and (@taxdt is not null)
                   THEN ISNULL((SELECT T0.BalDueDeb -T0.BalDueCred
                    WHERE DateDiff(mm, T0.TaxDate, @taxdt) = 0 ) ,0)
    END AS 'Current Mth', 
    CASE
                   WHEN (@refdt is not null) and (@taxdt is null)
                   THEN ISNULL((SELECT T0.BalDueDeb -T0.BalDueCred
                   WHERE DateDiff(mm, T0.RefDate, @refdt) = 1 ) ,0)
                   WHEN (@refdt is null) and (@taxdt is not null)
                   THEN ISNULL((SELECT T0.BalDueDeb -T0.BalDueCred
                    WHERE DateDiff(mm, T0.TaxDate, @taxdt) = 1 ) ,0)
    END AS '1 Mth Ago'
    /* Similarly for other age buckets  */
    FROM company1.dbo.JDT1 T0
    INNER JOIN company1.dbo.OCRD T1 ON T0.ShortName = T1.CardCode
    LEFT OUTER JOIN company1.dbo.OCPR T2 ON T1.CardCode = T2.Cardcode
    LEFT OUTER JOIN company1.dbo.OJDT T3 ON T0.TransID = T3.TransID
    LEFT OUTER JOIN company1.dbo.OINV  T4 ON T3.TransID = T4.TransID
    LEFT OUTER JOIN company1.dbo.ORIN  T5 ON T3.TransID = T5.TransID
    WHERE
    T1.CardType = 'C' and Balance != 0
    and (T0.BalDueDeb - T0.BalDueCred) != 0

    HI
    I generate the next aged analysis
    CREATE PROCEDURE [dbo].[Aged_Analysis] (@end datetime,@Client VarChar (20)) AS
    BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    Declare @SAPUNION Table (SN VarChar(50), TransId Int, ReconSum Decimal(19,2), DebHab VarChar(1),
                                       Linea Int)
    insert into @SAPUNION
    SELECT X0.ShortName 'SN', X0.TransId 'TransId', SUM(X0.ReconSum)'ReconSum', X0.IsCredit 'DebHab', X0.TransRowId 'Linea'
                FROM ITR1 X0
                INNER JOIN OITR X1 ON X1.ReconNum = X0.ReconNum
                WHERE X1.ReconDate <= @end  AND X1.CancelAbs = ''
                GROUP BY X0.ShortName, X0.TransId, X0.IsCredit, X0.TransRowId
    SELECT T0.CardCode, T0.CardName,T0.Address,T0.CreditLine,
    T1.TransId , T4.BaseRef , T1.Ref2 , T1.RefDate, T1.DueDate,
    CASE
          WHEN T3.DebHab = 'D'  THEN T1.Debit-T1.Credit-T3.ReconSum
          WHEN T3.DebHab = 'C'  THEN T1.Debit-T1.Credit+T3.ReconSum
          ELSE (T1.Debit-T1.Credit)
    END 'Balance',
    CASE
           when DateDiff(Day,t1.RefDate,GetDate()) <= 30 and T3.DebHab = 'D'  then T1.Debit-T1.Credit-T3.ReconSum
           when DateDiff(Day,t1.RefDate,GetDate()) <= 30 and T3.DebHab = 'C'  then T1.Debit-T1.Credit+T3.ReconSum
           when DateDiff(Day,t1.RefDate,GetDate()) <= 30 then (T1.Debit-T1.Credit) end '0-30 dias',
    CASE
           when DateDiff(Day,t1.refdate,GetDate()) between 31 and 45 and T3.DebHab = 'D'  then T1.Debit-T1.Credit-T3.ReconSum
           when DateDiff(Day,t1.refdate,GetDate()) between 31 and 45 and T3.DebHab = 'C'  then T1.Debit-T1.Credit+T3.ReconSum
           when DateDiff(Day,t1.refdate,GetDate()) between 31 and 45 then (T1.Debit-T1.Credit) end '31-45 dias',
    CASE
           when DateDiff(Day,t1.refdate,GetDate()) between 46 and 60 and T3.DebHab = 'D'  then T1.Debit-T1.Credit-T3.ReconSum
           when DateDiff(Day,t1.refdate,GetDate()) between 46 and 60 and T3.DebHab = 'C'  then T1.Debit-T1.Credit+T3.ReconSum
           when DateDiff(Day,t1.refdate,GetDate()) between 46 and 60 then (T1.Debit-T1.Credit) end '46-60 dias',
    CASE
           when DateDiff(Day,t1.refdate,GetDate()) between 61 and 75 and T3.DebHab = 'D'  then T1.Debit-T1.Credit-T3.ReconSum
           when DateDiff(Day,t1.refdate,GetDate()) between 61 and 75 and T3.DebHab = 'C'  then T1.Debit-T1.Credit+T3.ReconSum
           when DateDiff(Day,t1.refdate,GetDate()) between 61 and 75 then (T1.Debit-T1.Credit) end '61-75 dias',
    CASE
           when DateDiff(Day,t1.refdate,GetDate()) BETWEEN 76 AND 89 and T3.DebHab = 'D'  then T1.Debit-T1.Credit-T3.ReconSum
           when DateDiff(Day,t1.refdate,GetDate()) BETWEEN 76 AND 89 and T3.DebHab = 'C'  then T1.Debit-T1.Credit+T3.ReconSum
           when DateDiff(Day,t1.refdate,GetDate()) BETWEEN 76 AND 89 then (T1.Debit-T1.Credit) end '76-89 dias',
    CASE
           when DateDiff(Day,t1.refdate,GetDate()) >90 and T3.DebHab = 'D'  then T1.Debit-T1.Credit-T3.ReconSum
           when DateDiff(Day,t1.refdate,GetDate()) >90 and T3.DebHab = 'C'  then T1.Debit-T1.Credit+T3.ReconSum
           when DateDiff(Day,t1.refdate,GetDate()) >90 then (T1.Debit-T1.Credit) end '90-Mas',
    CASE T1.TransType
          WHEN '13' THEN (SELECT Y.Comments FROM OINV Y WHERE Y.TransId = T1.TransId)
          WHEN '14' THEN (SELECT Y.Comments FROM ORIN Y WHERE Y.TransId = T1.TransId)
          WHEN '24' THEN (SELECT Y.Comments FROM ORCT Y WHERE Y.TransId = T1.TransId)
          ELSE T1.LineMemo
    END 'Comments'
    FROM OCRD T0
          INNER JOIN JDT1 T1 ON T1.ShortName = T0.CardCode
          INNER JOIN OACT T2 ON T2.AcctCode = T1.Account
          INNER JOIN OJDT T4 ON T4.TransId = T1.TransId
          LEFT JOIN OINV T5 ON T5.TransId = T4.TransId  and t5.ObjType = t4.TransType     
          LEFT JOIN @SAPUNION T3 ON T3.TransId = T1.TransId AND T3.SN = T1.ShortName AND T3.Linea = T1.Line_ID
    WHERE T0.CardType = 'C' /*FOR CLIENTS*/ AND T1.RefDate <= @end AND T2.AcctCode = /*YOUR CLIENT ACCOUNT*/ AND
    (CASE
          WHEN T3.DebHab = 'D' THEN (T1.Debit-T1.Credit-T3.ReconSum)
          WHEN T3.DebHab = 'C' THEN (T1.Debit-T1.Credit+T3.ReconSum)
          ELSE (T1.Debit-T1.Credit)
    END) != '0'
    AND T0.CardCode= @Client
    ORDER BY T0.CardCode,T1.TransId,t1.Ref2
    END
    AND Execute by SAP
    DECLARE @VAR INT, @DATE DATETIME, @BP VARCHAR(8)
    SET @VAR = (SELECT TOP 1 T.DocEntry FROM [dbo].[OINV] T WHERE T.DocDate <='[%0]' AND T.CardCode='[%1]')
    SET @DATE = '[%0]'
    SET @BP = '[%1]'
    EXECUTE [dbo].[Aged_Analysis]
    @end = @DATE,
    @Client = @BP
    Regards
    Floyola
    Edited by: Floyola on Jul 22, 2011 10:17 AM

  • Update or select in a single query

    Hi , I want to select or update from a single query. Can I do that ?
    I tried Merge into, but it is for Update or Insert.
    Can anyone help me please. I do not want to use stored Proc/function.

    userPrasad wrote:
    I want to fire a update or merge statement inside a select SQL. Is there any way to do that ?Just to clarify:
    It is possible to UPDATE based on a SELECT condition within SQL, i.e.,
    UPDATE table1 t1
       SET col1 = new_val
    WHERE col2 IN (
        SELECT col2
           FROM table2 t2
          WHERE t1.col1 = t2.col1
              AND col1 = old_val);or to MERGE:
    MERGE into table1 t1
    USING (SELECT * FROM table2) t2
      ON (t1.col1 = t2.col1)
    WHEN MATCHED...
    WHEN NOT MATCHED...Both of those will use a SELECT, and MERGE can UPDATE, INSERT, both or either one, or none.
    Is that what you had in mind?

  • Is it possible to run 2 different reports SEPARATELY from a single query?

    Dear All,
    The title to my previous thread seems to be inaccurate and misleading.
    To encourage people to read it, I am giving it a more appropriate Title.
    Please do not reply on this thread, but refer to the original one.
    Thanks
    Leon Lai
    Here's the link:
    Is it possible to combine 2 different reports in a single Query?

    Dear All,
    The title to my previous thread seems to be inaccurate and misleading.
    To encourage people to read it, I am giving it a more appropriate Title.
    Please do not reply on this thread, but refer to the original one.
    Thanks
    Leon Lai
    Here's the link:
    Is it possible to combine 2 different reports in a single Query?

  • 'dbms_xplan.display_awr' is showing two plan for single query

    Hi,
    I am trying to fetch sql plan from awr, but it's showing two different plans for a single query:
    PLAN_TABLE_OUTPUT
    SQL_ID 2pxv33cr271sb
    SELECT P_DEP_BNK_CODE,P_DEP_BRN_CODE,P_DEP_DATE,
                                   P_DEP_DAY_SL,P_DEP_INST_SL,P_INST_AMT                                       
                             FROM P WHERE
                                        P_DEP_BNK_CODE = :1 AND
                                    P_DEP_BRN_CODE = :2 AND
                                P_DEP_DATE     = :3 AND
                            P_DEP_LCC_UCC  = :4 AND
                        P_DEP_DAY_SL   = :5 AND
                    (P_REALISED_ON IS NULL AND
                    P_RTN_DATE IS NULL)
    Plan hash value: 3064382432
    | Id  | Operation                          | Name      | Rows  | Bytes | Cost (%CPU)| Time     | Pstart| Pstop |
    |   0 | SELECT STATEMENT                   |           |       |       |     5 (100)|          |       |       |
    |   1 |  TABLE ACCESS BY GLOBAL INDEX ROWID| P         |     1 |    40 |     5   (0)| 00:00:01 | ROWID | ROWID |
    |   2 |   INDEX RANGE SCAN                 | P_PK      |     1 |       |     4   (0)| 00:00:01 |       |       |
    Note
       - dynamic sampling used for this statement (level=5)
    SQL_ID 2pxv33cr271sb
    SELECT P_DEP_BNK_CODE,P_DEP_BRN_CODE,P_DEP_DATE,
                                   P_DEP_DAY_SL,P_DEP_INST_SL,P_INST_AMT                                       
                             FROM P WHERE
                                        P_DEP_BNK_CODE = :1 AND
                                    P_DEP_BRN_CODE = :2 AND
                                P_DEP_DATE     = :3 AND
                            P_DEP_LCC_UCC  = :4 AND
                        P_DEP_DAY_SL   = :5 AND
                    (P_REALISED_ON IS NULL AND
                    P_RTN_DATE IS NULL)
    Plan hash value: 3447007225
    | Id  | Operation            | Name     | Rows  | Bytes | Cost (%CPU)| Time     | Pstart| Pstop |    TQ  |IN-OUT| PQ Distrib |
    |   0 | SELECT STATEMENT     |          |       |       |     7 (100)|          |       |       |        |      |            |
    |   1 |  PX COORDINATOR      |          |       |       |            |          |       |       |        |      |            |
    |   2 |   PX SEND QC (RANDOM)| :TQ10000 |     1 |    38 |     7  (43)| 00:00:01 |       |       |  Q1,00 | P->S | QC (RAND)  |
    |   3 |    PX BLOCK ITERATOR |          |     1 |    38 |     7  (43)| 00:00:01 |   KEY |   KEY |  Q1,00 | PCWC |            |
    |   4 |     TABLE ACCESS FULL| P        |     1 |    38 |     7  (43)| 00:00:01 |   KEY |   KEY |  Q1,00 | PCWP |            |
    ------------------------------------------------------------------------------------------------------------------------------The database version is 11.2.0.1 and the underlying table is partitioned. Why this is showing two plans? Although the plan doesn't look expensive but this is causing maximum gets and enq: row lock contention
    Regards,
    Regards

    SQL> set autot on
    SQL> SELECT
      2  SUM(NVL(P_INST_AMT, 0))
      3  FROM
      4  AXISCMS.P
      5  WHERE
      6  P_DEP_BNK_CODE = '211'
      7  AND
      8  P_DEP_BRN_CODE = '005'
      9  AND
    10  P_DEP_DATE = to_date('11-NOV-2010')
    11  AND
    12  P_DEP_LCC_UCC = 'L'
    13  AND
    P_DEP_DAY_SL = 15001
    14   15  AND
    16  (P_REALISED_ON IS NOT NULL OR P_RTN_DATE IS NOT NULL );
    SUM(NVL(P_INST_AMT,0))
    Execution Plan
    | Id  | Operation                           | Name      | Rows  | Bytes | Cost  | Pstart| Pstop |
    |   0 | SELECT STATEMENT                    |           |     1 |    38 |     8 |       |       |
    |   1 |  SORT AGGREGATE                     |           |     1 |    38 |       |       |       |
    |   2 |   TABLE ACCESS BY GLOBAL INDEX ROWID| P          |     1 |    38 |     8 |    72 |    72 |
    |   3 |    INDEX RANGE SCAN                 | P_PK      |     1 |       |     4 |       |       |
    Note
       - 'PLAN_TABLE' is old version
    Statistics
              5  recursive calls
              0  db block gets
            370  consistent gets
             31  physical reads
              0  redo size
            543  bytes sent via SQL*Net to client
            524  bytes received via SQL*Net from client
              2  SQL*Net roundtrips to/from client
              0  sorts (memory)
              0  sorts (disk)
              1  rows processedThe above query seems to be having cheapest cost but causing a lot of slowness in the database.
    Column Description:
    COLUMN_NAME                    DATA_TYPE                      NUM_DISTINCT  NUM_NULLS    DENSITY HISTOGRAM
    P_AC_NAME                 VARCHAR2                             244672   49251591 4.0871E-06 NONE
    P_AC_NO                   VARCHAR2                             413792   48713721 2.4167E-06 NONE
    P_ARNGMNT_CREDIT_DATE     DATE                                   1708   39366743 .001724138 HEIGHT BALANCED
    P_AUTOLIQ_ACT_DATE        DATE                                    358   50356077 .003003003 HEIGHT BALANCED
    P_AUTOLIQ_DUE_DATE        DATE                                    337   50427426 .002967359 NONE
    P_AUTOLIQ_FLAG            CHAR                                      1   44746714          1 NONE
    P_CLG_DNLD_FLAG           NUMBER                                    1   50481119 .035714286 FREQUENCY
    P_CORR_BANK_REAL_DATE     DATE                                      0   50481133          0 NONE
    P_DEP_BNK_CODE            VARCHAR2                                 16          0 9.9454E-09 FREQUENCY
    P_DEP_BRN_CODE            VARCHAR2                                671          0 .002531646 HEIGHT BALANCEDIndex Details
    INDEX_NAME                     COLUMN_NAME                    COLUMN_POSITION
        P_IDX_FULL                P_INST_NO                               1
        P_IDX_FULL                P_DRAWN_ON_BANK                         2
        P_IDX_FULL                P_DRAWN_ON_BRN                          3
        P_IDX_FULL                P_INST_TYPE                             4
        P_IDX_FULL                P_DRAWN_ON_LOC                          5
        P_IDX_FULL                P_RTN_DATE                              6
        P_INDX1                   P_INST_NO                               1
        P_INDX2                   P_RTN_DATE                              1
        P_INDX2                   P_RTN_DAY_SL                            2
        P_INDX2                   P_RTN_INS_SL                            3
        P_INDX3                   P_REALISED_ON                           1
        P_INDX3                   P_REALISED_DAY_SL                       2
        P_INDX3                   P_REALISED_INS_SL                       3
        P_INDX4                   P_REV_TO_COL_DUE_DATE                   1
        P_INDX4                   P_REV_TO_COL_DONE_ON                    2
        P_INDX5                   P_ARNGMNT_CREDIT_DATE                   1
        P_INDX6                   P_POOL_POST_DATE                        1
        P_INDX6                   P_POOL_POST_DAYSL                       2
        P_PK                      P_DEP_BNK_CODE                          1
        P_PK                      P_DEP_BRN_CODE                          2
        P_PK                      P_DEP_DATE                              3
        P_PK                      P_DEP_LCC_UCC                           4
        P_PK                      P_DEP_DAY_SL                            5
        P_PK                      P_DEP_INST_SL                           6
    Top 5 Timed Foreground Events
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
                                                               Avg
                                                              wait   % DB
    Event                                 Waits     Time(s)   (ms)   time Wait Class
    DB CPU                                           58,454          13.1
    enq: TX - row lock contention         1,095      17,691  16156    4.0 Applicatio
    read by other session             1,719,661      11,392      7    2.6 User I/O
    latch: cache buffers chains         264,753      10,758     41    2.4 Concurrenc
    latch free                           78,456       8,215    105    1.8 Other
    The query comes on top in every section in AWR.Regards,

  • Selecting data from single table with different condition in single query

    Hi everybody...
    I have one table with col1, col2, col3, col4, col5... as columns.
    I want to select col1, col2, col3 with condition (x=y and a=b and c=d)
    I want to select col4, col5 with condition (x=y and a=b and m=n )
    in single query...
    Thanx for ur help

    Given this data set...
    SQL> select * from oddity
      2  /
          COL1       COL2       COL3       COL4       COL5 A X C M
             1          2          3          4          5 B Y   M
             1          2          3          4          5 A Y C N
             1          2          3          4          5 A Y D M
             1          2          3          4          5 A Y D N
             1          2          3          4          5 B Y D N
             1          2          3          4          5 B Y D U
    6 rows selected.
    SQL>The following query meets the requirements. Of course, the requirements as stated are incomplete. I ahave assumed that we select all five columns if C=D andM=N.
    SQL> SELECT decode(c, 'D', col1, '0') AS col1
      2         , decode(c, 'D', col2, '0') AS col2
      3         , decode(c, 'D', col3, '0') AS col3
      4          , decode(m, 'N', col4, '-8') AS col4
      5           , decode(m, 'N', col5, '-8') AS col5
      6  FROM oddity
      7  WHERE a = 'B'
      8  AND  x = 'Y'
      9  /
          COL1       COL2       COL3       COL4       COL5
             0          0          0         -8         -8
             1          2          3          4          5
             1          2          3         -8         -8
    SQL> Cheers, APC

  • Select single query working unexpectedly

    Hi all,
    I have used below select single * query as shown :
    I have data in my table S022 as shown below, it has 2 records for material and aufnr combination :
    WERKS  ARBPL    kapar    MATNR                AUFNR      
    w1        ar1        004          mat1             000300156789
    w1        ar2                        mat1             000300156789
    The code used :
    select single *               
       from s022                   
      where werks = itab-ltap-werks  "w1
        and matnr = w_matnr         "mat1
        and aufnr = w_aufnr. " 000300156789
    runtime select query is picking second record i.e of ar2.
    I hope it should have picked ar1 record but its doesnt .
    Also sometimes it picks 1st record for different data and for this data it picks the second record.
    Kindly help me to explain why its not picking the first record.
    Regards.

    ujjwal_d15 wrote:
    It is as per the data in the table . The records are one below the another in database table.
    > So i feel it should have picked the first record.
    Hello Ujjwal,
    The records shown in the databrowser is a snapshot of the entries in the DB & not how the recs are actually stored!
    In RDBMS the sequence of entries is not defined at the DB layer. In SELECT SINGLE the 1st rec to be hit is returned to the result set. In your case this is the 2nd rec.
    BR,
    Suhas

  • Single Query for getting total no of records N getting records from a selected range

    Hi,
    Got the below query:
    SELECT a.*, rowid FROM (SELECT name, postcode FROM Tbl ORDER BY name asc)a WHERE ROWNUM <=30
    MINUS
    SELECT b.*, rowid FROM (SELECT name, postcode FROM Tbl ORDER BY name asc) b WHERE ROWNUM <= 10
    Though I got the results right, I also want to know the total no of records from "SELECT name, postcode FROM Tbl ORDER BY name asc". Does anyone knows how to do it in a single query?
    Thanks.

    hi Carol
    The following output may help you.
    SQL> l
    1 select * from emp where (rowid,0) in (select rowid,mod(rownum,10)-rownum from emp)
    2 minus
    3* select * from emp where (rowid,0) in (select rowid,mod(rownum,6)-rownum from emp)
    SQL> /
    EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
    7839 KING PRESIDENT 17-NOV-81 5000 10
    7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
    7876 ADAMS CLERK 7788 12-JAN-83 1100 20
    7900 JAMES CLERK 7698 03-DEC-81 950 30
    The above query fetches the 6,7,8,9th records only.
    Well my suggestion would be not to use ROWNUM directly in where clause since it changes dynamically. it is not a fixed value. for example pls see the result.
    SQL> select rownum,empno,ename,sal,job from emp where sal > 3000;
    ROWNUM EMPNO ENAME SAL JOB
    1 7839 KING 5000 PRESIDENT
    SQL> select rownum,empno,ename,sal,job from emp where sal > 1000;
    ROWNUM EMPNO ENAME SAL JOB
    1 7566 JONES 2975 MANAGER
    2 7654 MARTIN 1250 SALESMAN
    3 7698 BLAKE 2850 MANAGER
    4 7782 CLARK 2450 MANAGER
    5 7788 SCOTT 3000 ANALYST
    6 7839 KING 5000 PRESIDENT
    7 7844 TURNER 1500 SALESMAN
    8 7876 ADAMS 1100 CLERK
    9 7902 FORD 3000 ANALYST
    10 7934 MILLER 1300 CLERK
    10 rows selected.
    SQL> select * from emp where rownum = 1;
    EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
    7566 JONES MANAGER 7839 02-APR-81 2975 20
    The record of employee KING is getting the rownum differently.
    My understanding (out of my little knowledge) is the rownum values are assigned to the records only after the records are read physically and after applying the conditions(without rownum). Then the row numbers (rownum) is assigned to the records. Hence the rownum is not constant to a record since it is a dynamic value.
    Well i would like to know the suggestions of the ORACLE EXPERTS here in the discussion forum.
    If my finding is correct then OK if not Pls excuse me and pls give the correct solution
    Regards
    Prakash Eranki
    [email protected]

  • All selected 'n' consecutive rows in retrieved in a single query

    hello,
    I have table T with 50,000 rows
    create table T
    (student_id number,
    class_id number,
    quiz_id number,
    marks number)
    some sample rows like
    INSERT INTO T VALUES (1,1, 1, 50);
    INSERT INTO T VALUES (2,2, 2, 40);
    INSERT INTO T VALUES (3,1, 3, 34);
    INSERT INTO T VALUES (1,1, 4, 10);
    INSERT INTO T VALUES (1,1, 5, 30);
    INSERT INTO T VALUES (1,1, 6, ‘29);
    INSERT INTO T VALUES (3,2, 7, 34);
    INSERT INTO T VALUES (3,2, 8, 33);
    INSERT INTO T VALUES (3,2, 9, 56);
    INSERT INTO T VALUES (1,1, 7, 90);
    INSERT INTO T VALUES (2,2, 8, 0,);
    INSERT INTO T VALUES (1,1, 8, 80);
    INSERT INTO T VALUES (2,2, 8, 65);
    INSERT INTO T VALUES (1,1, 9, ‘34);
    INSERT INTO T VALUES (2,2, 9, 11);each student belongs to one class_id. each student participates in many quizes. each quiz has its unique id. each student can appear once in a quiz_id
    I am doing the below analysis and query:
    1. with below query I am finding which student_id had most marks in any 3 successive quizes (see the 3-1 part below) in the query..
    SELECT QUIZ_ID,
          STUDENT_ID,
    SUM (MARKS) OVER (PARTITION BY STUDENT_ID ORDER BY QUIZ_ID1
    RANGE BETWEEN CURRENT ROW AND (3-1) FOLLOWING) consecMARKS , MARKS   FROM
          (SELECT QUIZ_ID,
            STUDENT_ID,
            MARKS,
          ROW_NUMBER() OVER (PARTITION BY STUDENT_ID ORDER BY T.QUIZ_ID) QUIZ_ID1
          FROM T
          WHERE MARKS IS NOT NULL
          ORDER BY 1
        ORDER BY 3 DESC
    SQL> /
       QUIZ_ID STUDENT_ID CONSECMARKS
             7          1         170
             6          1         166
             8          1         129
             5          1         106
             8          3          89
             8          2          76
             3          3          68
             7          3          67
             8          2          65
             1          1          60
             9          3          56
       QUIZ_ID STUDENT_ID CONSECMARKS
             9          1          49
             2          2          40
             4          1          40
             9          2          11
    15 rows selected.With above query, I can play around and find for any 'n' number of consecutive quizes, like marks in 2 consecutives quizes, 3, 4 and so on but for each 'n' value I've to run a seperate query mentioning (2-1) or (3-1) or (4-1) and so on..
    since my table is big and there are about 400 quizes so what I want to find out is for each 'n' consecutive quiz (from 1 to 400) which student had most marks for each consecutie 'n' quiz. Like in 1 (consecutive) quiz which student had the highest marks and then 2 conseuctive quiz who had most marks and then in 3 consecutive quiz who had most marks and so on till 400 consecutive quiz who had most marks... rather than running query for each 'n' value seperately i want a single query that can give me a summary of most marks in each n consecutive quizes...
    my sample output is:
    Nth consecutive quiz     student_id    sum(marks)
    1                        1              90
    2                        1              170
    3                        1              246
    4
    100
    200
    300
    400                      ?              ?   Is this possible to get the above output from one single query? If there are two or more students with equal most marks for any 'n' conseutive quizes then both should come in the summary.
    Hope I have been able to put up my question clearly.
    regards
    Ramis

    Something like:
    SELECT  N,
            QUIZ_ID,
            STUDENT_ID,
            SUM(MARKS) OVER (PARTITION BY N,STUDENT_ID ORDER BY QUIZ_ID1 RANGE BETWEEN CURRENT ROW AND (N-1) FOLLOWING) consecMARKS,
            MARKS
      FROM  (SELECT  QUIZ_ID,
                     STUDENT_ID,
                     MARKS,
                     ROW_NUMBER() OVER (PARTITION BY STUDENT_ID ORDER BY T.QUIZ_ID) QUIZ_ID1
               FROM  T
               WHERE MARKS IS NOT NULL
             SELECT  LEVEL N
               FROM  DUAL
               CONNECT BY LEVEL <= (
                                    SELECT  COUNT(DISTINCT QUIZ_ID)
                                      FROM  T
        ORDER BY N,
                 consecMARKS DESC
             N    QUIZ_ID STUDENT_ID CONSECMARKS      MARKS
             1          7          1          90         90
             1          8          1          80         80
             1          8          2          65         65
             1          9          3          56         56
             1          1          1          50         50
             1          2          2          40         40
             1          9          1          34         34
             1          7          3          34         34
             1          3          3          34         34
             1          8          3          33         33
             1          5          1          30         30
             N    QUIZ_ID STUDENT_ID CONSECMARKS      MARKS
             1          6          1          29         29
             1          9          2          11         11
             1          4          1          10         10
             1          8          2           0          0
             2          7          1         170         90
             2          6          1         119         29
             2          8          1         114         80
             2          8          3          89         33
             2          8          2          76         65
             2          3          3          68         34
             2          7          3          67         34
             N    QUIZ_ID STUDENT_ID CONSECMARKS      MARKS
             2          8          2          65          0
             2          1          1          60         50
             2          5          1          59         30
             2          9          3          56         56
             2          2          2          40         40
             2          4          1          40         10
             2          9          1          34         34
             2          9          2          11         11
             3          7          1         204         90
             3          6          1         199         29
             3          5          1         149         30
             N    QUIZ_ID STUDENT_ID CONSECMARKS      MARKS
             3          7          3         123         34
             3          8          1         114         80
             3          2          2         105         40
             3          3          3         101         34
             3          1          1          90         50
             3          8          3          89         33
             3          8          2          76         65
             3          8          2          76          0
             3          4          1          69         10
             3          9          3          56         56
             3          9          1          34         34
             N    QUIZ_ID STUDENT_ID CONSECMARKS      MARKS
             3          9          2          11         11
             4          6          1         233         29
             4          5          1         229         30
             4          7          1         204         90
             4          4          1         159         10
             4          3          3         157         34
             4          7          3         123         34
             4          1          1         119         50
             4          2          2         116         40
             4          8          1         114         80
             4          8          3          89         33
             N    QUIZ_ID STUDENT_ID CONSECMARKS      MARKS
             4          8          2          76          0
             4          8          2          76         65
             4          9          3          56         56
             4          9          1          34         34
             4          9          2          11         11
             5          5          1         263         30
             5          4          1         239         10
             5          6          1         233         29
             5          1          1         209         50
             5          7          1         204         90
             5          3          3         157         34
             N    QUIZ_ID STUDENT_ID CONSECMARKS      MARKS
             5          7          3         123         34
             5          2          2         116         40
             5          8          1         114         80
             5          8          3          89         33
             5          8          2          76          0
             5          8          2          76         65
             5          9          3          56         56
             5          9          1          34         34
             5          9          2          11         11
             6          1          1         289         50
             6          4          1         273         10
             N    QUIZ_ID STUDENT_ID CONSECMARKS      MARKS
             6          5          1         263         30
             6          6          1         233         29
             6          7          1         204         90
             6          3          3         157         34
             6          7          3         123         34
             6          2          2         116         40
             6          8          1         114         80
             6          8          3          89         33
             6          8          2          76          0
             6          8          2          76         65
             6          9          3          56         56
             N    QUIZ_ID STUDENT_ID CONSECMARKS      MARKS
             6          9          1          34         34
             6          9          2          11         11
             7          1          1         323         50
             7          4          1         273         10
             7          5          1         263         30
             7          6          1         233         29
             7          7          1         204         90
             7          3          3         157         34
             7          7          3         123         34
             7          2          2         116         40
             7          8          1         114         80
             N    QUIZ_ID STUDENT_ID CONSECMARKS      MARKS
             7          8          3          89         33
             7          8          2          76          0
             7          8          2          76         65
             7          9          3          56         56
             7          9          1          34         34
             7          9          2          11         11
             8          1          1         323         50
             8          4          1         273         10
             8          5          1         263         30
             8          6          1         233         29
             8          7          1         204         90
             N    QUIZ_ID STUDENT_ID CONSECMARKS      MARKS
             8          3          3         157         34
             8          7          3         123         34
             8          2          2         116         40
             8          8          1         114         80
             8          8          3          89         33
             8          8          2          76          0
             8          8          2          76         65
             8          9          3          56         56
             8          9          1          34         34
             8          9          2          11         11
             9          1          1         323         50
             N    QUIZ_ID STUDENT_ID CONSECMARKS      MARKS
             9          4          1         273         10
             9          5          1         263         30
             9          6          1         233         29
             9          7          1         204         90
             9          3          3         157         34
             9          7          3         123         34
             9          2          2         116         40
             9          8          1         114         80
             9          8          3          89         33
             9          8          2          76          0
             9          8          2          76         65
             N    QUIZ_ID STUDENT_ID CONSECMARKS      MARKS
             9          9          3          56         56
             9          9          1          34         34
             9          9          2          11         11
    135 rows selected.
    SQL> SY.

  • How to call the same query more than once with different selection criteria

    Hi,
    Please do anybody know how to solve this issue? I need to call one query with the fixed structure more than once with different selection criteria. For example. I have following data
    Sales organization XX
                         Income 2008  Income 2009
    Customer A       10                 20
    Customer B        30                  0
    Sales organization YY
                         Income 2008  Income 2009
    Customer A        20                5
    Customer B        50                10
    Now, I need this. At the selection screen of query, user fill variable  charakteristic "Sales organization" with interval  XX - YY, than I need to generate two separate results per sales organization, one for Sales Organization XX and the second for SO YYwhich will be displayed each on separate page, where result for SO YY will be dispayed under result for SO YY. Are there some options how to do it for example in Report Designer or WAD or with programming? In Report Designer is possible to use one query more than once, but I dont know how to force each query in RD to display result only for one Sales Organization, which will be defined in selection screen.
    Thank you very much
    J.

    Hello,
    thanks to all for cooperation. Finally we solved this issue with the following way..
    User fill appropriate SO on the selection screen, which is defined as range. This will resulte, that selected SO are listed in report below each othe (standard behavior). Required solution we achieved with the Report Designer, we set page break under each Result row of RD. This caused, that report is divided into required part per SO, which are stated each on separate page.
    J.

  • Distinct data from different columns of a table-Single query

    I have a table with different columns. Each of these columns have entries. A particular column, say, a column called name can have same entries more than one time. Likewise other columns can also have same entries more than once. My requirement is to have distinct entries from each of these columns using a single query, such that , for eg; the name column will contain the name George only once on retrieval. Place column will have the place Newyork only once...like that...but Newyork and newyork should be treated different(likewise in other columns also ie; case sensitive). I want to retrieve the above said using a single query from a table. Kindly help.
    Regards,
    Anees

    You're asking a SQL question in a JDBC forum. Look for a SQL forum. The website of the database manfactuer may have a SQL forum/mailinglist.

  • Select top row in Single Query?

    Hi
    Can somebody help me to write a query to get the first row after order by clause using single query alone.
    Example:
    I can write following query to select first row
    select * from (selec * from t order by col1) where rownum = 1;
    But here I should not use inline view to get the result. Because my original requirement needs to use this query in select list and it needs to use a column (of a table from the FROM clause) in the where clause of inline query. Because there is restriction that we can not use the column (of a table from the FROM clause) more than one level of inline query.
    Please help me.

    Raghav.786 wrote:
    Hi
    Can somebody help me to write a query to get the first row after order by clause using single query alone.
    Example:
    I can write following query to select first row
    select * from (selec * from t order by col1) where rownum = 1;
    But here I should not use inline view to get the result. Because my original requirement needs to use this query in select list and it needs to use a column (of a table from the FROM clause) in the where clause of inline query. Because there is restriction that we can not use the column (of a table from the FROM clause) more than one level of inline query.
    Please help me.
    What Oracle version are you?
    If you have 12c you can use
    select col1,...
      from t
    order by col1
    fetch first 1 row only;
    If less than 12c, you have can't do it without a subquery.
    What are you actually trying to do? Read Re: 2. How do I ask a question on the forums?
    and follow the advice there by giving example create table and insert sample data statements and
    explaining clearly what you are trying to do. Then we can help more.

  • Dashboard having same query with different selection screen values

    Hi,
    I want to create a dashboard by including different versions (different selection screen values, like yesterday, last week, last month) of same query. Is it possible to achieve it by without creating separate queries? We are in BI 7.
    Thanks in advance
    Nisha

    Hi,
    I want to create a dashboard by including different versions (different selection screen values, like yesterday, last week, last month) of same query. Is it possible to achieve it by without creating separate queries? We are in BI 7.
    Thanks in advance
    Nisha

  • Update two different tables by a single sql query:

    Hi All,
    i need to update two different talbes in a single sql query..
    i m using the following query
    UPDATE FT_User_Alert SET Subscription = 'W' where product_key=1 and measure_key = 12
    AND
    UPDATE LU_Monthly_Alert_Budget_Sheet SET Min_Red_Range ='16.0' AND Max_Green_Range ='24.0'AND Max_Red_Range ='27.0'AND Min_Green_Range ='16.0' where product_key='1' and measure_key = 12
    i m getting the following error:
    Odbc driver returned an error (SQLExecDirectW).
    Error Details
    Error Codes: OPR4ONWY:U9IM8TAC:OI2DL65P
    State: HY000. Code: 10058. [NQODBC] [SQL_STATE: HY000] [nQSError: 10058] A general error has occurred. [nQSError: 43093] An error occurred while processing the EXECUTE PHYSICAL statement. [nQSError: 17001] Oracle Error code: 936, message: ORA-00936: missing expression at OCI call OCIStmtExecute: UPDATE FT_User_Alert SET Subscription = 'W' where product_key=1 and measure_key = 12 AND UPDATE LU_Monthly_Alert_Budget_Sheet SET Min_Red_Range ='16.0' AND Max_Green_Range ='24.0'AND Max_Red_Range ='27.0'AND Min_Green_Range ='16.0' where product_key='1' and measure_key = 12 . [nQSError: 17011] SQL statement execution failed. (HY000)
    SQL Issued: EXECUTE PHYSICAL CONNECTION POOL writeback UPDATE FT_User_Alert SET Subscription = 'W' where product_key=1 and measure_key = 12 AND UPDATE LU_Monthly_Alert_Budget_Sheet SET Min_Red_Range ='16.0' AND Max_Green_Range ='24.0'AND Max_Red_Range ='27.0'AND Min_Green_Range ='16.0' where product_key='1' and measure_key = 12
    but when i m ushin the same query in Microsoft SQL Server it executes properly:
    please help me out...

    Duplicate thread. I've already answered on your other thread...
    update two different tables by a single sql query:

  • Need different rows from single query based on condition

    Hi,
    I have a table with 100 rows that holds employees and their roles.
    I need to write a SQL(not a PL/SQL block) as below
    1. When employee with role 'VP' logs in, the query should return all the 100 rows.
    2. When employee with role 'MGR' logs in, the query should return only those rows whose MGR is the logged in employee.
    3. When employee with role 'SALE_EXEC' logs in, it should return single rows corresponding to this SALE_EXEC.
    My requirement here is to get these outputs from a single query.
    Can anyone please help me with this.
    Thanks,
    Vivek.

    use vpd
    New Policy Groups
    When adding the policy to a table, view, or synonym, you can use the DBMS_RLS.ADD_GROUPED_POLICY interface to specify the group to which the policy belongs. To specify which policies will be effective, you add a driving context using the DBMS_RLS.ADD_POLICY_CONTEXT interface. If the driving context returns an unknown policy group, then an error is returned.
    If the driving context is not defined, then all policies are executed. Likewise, if the driving context is NULL, then policies from all policy groups are enforced. In this way, an application accessing the data cannot bypass the security setup module (which sets up application context) to avoid any applicable policies.
    You can apply multiple driving contexts to the same table, view, or synonym, and each of them will be processed individually. In this way, you can configure multiple active sets of policies to be enforced.
    Consider, for example, a hosting company that hosts Benefits and Financial applications, which share some database objects. Both applications are striped for hosting using a SUBSCRIBER policy in the SYS_DEFAULT policy group. Data access is partitioned first by subscriber ID, then by whether the user is accessing the Benefits or Financial applications (determined by a driving context). Suppose that Company A, which uses the hosting services, wants to apply a custom policy which relates only to its own data access. You could add an additional driving context (such as COMPANY A SPECIAL) to ensure that the additional, special policy group is applied for data access for Company A only. You would not apply this under the SUBSCRIBER policy, because the policy relates only to Company A, and it is more efficient to segregate the basic hosting policy from other policies.
    How to Implement Policy Groups
    To create policy groups, the administrator must do two things:
    Set up a driving context to identify the effective policy group.
    Add policies to policy groups as required.
    The following example shows how to perform these tasks.
    Note:
    You need to set up the following data structures for the examples in this section to work:
    DROP USER finance CASCADE;
    CREATE USER finance IDENTIFIED BY welcome2;
    GRANT RESOURCE TO apps;
    DROP TABLE apps.benefit;
    CREATE TABLE apps.benefit (c NUMBER);
    Step 1: Set Up a Driving Context
    Begin by creating a namespace for the driving context. For example:
    CREATE CONTEXT appsctx USING apps.apps_security_init;
    Create the package that administers the driving context. For example:
    CREATE OR REPLACE PACKAGE apps.apps_security_init IS
    PROCEDURE setctx (policy_group VARCHAR2);
    END;
    CREATE OR REPLACE PACKAGE BODY apps.apps_security_init AS
    PROCEDURE setctx ( policy_group varchar2 ) IS
    BEGIN
    REM Do some checking to determine the current application.
    REM You can check the proxy if using the proxy authentication feature.
    REM Then set the context to indicate the current application.
    DBMS_SESSION.SET_CONTEXT('APPSCTX','ACTIVE_APPS', policy_group);
    END;
    END;
    Define the driving context for the table APPS.BENEFIT.
    BEGIN
    DBMS_RLS.ADD_POLICY_CONTEXT('apps','benefit','APPSCTX','ACTIVE_APPS');
    END;
    Step 2: Add a Policy to the Default Policy Group.
    Create a security function to return a predicate to divide the data by company.
    CREATE OR REPLACE FUNCTION by_company (sch varchar2, tab varchar2)
    RETURN VARCHAR2 AS
    BEGIN
    RETURN 'COMPANY = SYS_CONTEXT(''ID'',''MY_COMPANY'')';
    END;
    Because policies in SYS_DEFAULT are always executed (except for SYS, or users with the EXEMPT ACCESS POLICY system privilege), this security policy (named SECURITY_BY_COMPANY), will always be enforced regardless of the application running. This achieves the universal security requirement on the table: namely, that each company should see its own data regardless of the application that is running. The function APPS.APPS_SECURITY_INIT.BY_COMPANY returns the predicate to make sure that users can only see data related to their own company:
    BEGIN
    DBMS_RLS.ADD_GROUPED_POLICY('apps','benefit','SYS_DEFAULT',
    'security_by_company',
    'apps','by_company');
    END;
    Step 3: Add a Policy to the HR Policy Group
    First, create the HR group:
    CREATE OR REPLACE FUNCTION hr.security_policy
    RETURN VARCHAR2
    AS
    BEGIN
    RETURN 'SYS_CONTEXT(''ID'',''TITLE'') = ''MANAGER'' ';
    END;
    The following creates the policy group and adds a policy named HR_SECURITY to the HR policy group. The function HR.SECURITY_POLICY returns the predicate to enforce security on the APPS.BENEFIT table:
    BEGIN
    DBMS_RLS.CREATE_POLICY_GROUP('apps','benefit','HR');
    DBMS_RLS.ADD_GROUPED_POLICY('apps','benefit','HR',
    'hr_security','hr','security_policy');
    END;
    Step 4: Add a Policy to the FINANCE Policy Group
    Create the FINANCE policy:
    CREATE OR REPLACE FUNCTION finance.security_policy
    RETURN VARCHAR2
    AS
    BEGIN
    RETURN ('SYS_CONTEXT(''ID'',''DEPT'') = ''FINANCE'' ');
    END;
    Create a policy group named FINANCE and add the FINANCE policy to the FINANCE group:
    BEGIN
    DBMS_RLS.CREATE_POLICY_GROUP('apps','benefit','FINANCE');
    DBMS_RLS.ADD_GROUPED_POLICY('apps','benefit','FINANCE',
    'finance_security','finance', 'security_policy');
    END;
    As a result, when the database is accessed, the application initializes the driving context after authentication. For example, with the HR application:
    execute apps.security_init.setctx('HR');
    Validating the Application Used to Connect to the Database
    The package implementing the driving context must correctly validate the application that is being used to connect to the database. Although the database always checks the call stack to ensure that the package implementing the driving context sets context attributes, inadequate validation can still occur within the package.
    For example, in applications where database users or enterprise users are known to the database, the user needs the EXECUTE privilege on the package that sets the driving context. Consider a user who knows that:
    The BENEFITS application allows more liberal access than the HR application
    The setctx procedure (which sets the correct policy group within the driving context) does not perform any validation to determine which application is actually connecting. That is, the procedure does not check either the IP address of the incoming connection (for a three-tier system) or the proxy_user attribute of the user session.
    Such a user could pass to the driving context package an argument setting the context to the more liberal BENEFITS policy group, and then access the HR application instead. Because the setctx does no further validation of the application, this user bypasses the normally more restrictive HR security policy.
    By contrast, if you implement proxy authentication with VPD, then you can determine the identity of the middle tier (and the application) that is actually connecting to the database on behalf of a user. In this way, the correct policy will be applied for each application to mediate data access.
    For example, a developer using the proxy authentication feature could determine that the application (the middle tier) connecting to the database is HRAPPSERVER. The package that implements the driving context can thus verify whether the proxy_user in the user session is HRAPPSERVER. If so, then it can set the driving context to use the HR policy group. If proxy_user is not HRAPPSERVER, then it can disallow access.
    In this case, when the following query is executed
    SELECT * FROM APPS.BENEFIT;
    Oracle Database picks up policies from the default policy group (SYS_DEFAULT) and active namespace HR. The query is internally rewritten as follows:
    SELECT * FROM APPS.BENEFIT WHERE COMPANY = SYS_CONTEXT('ID','MY_COMPANY') and SYS_CONTEXT('ID','TITLE') = 'MANAGER';
    How to Add a Policy to a Table, View, or Synonym
    The DBMS_RLS package enables you to administer security policies by using its procedures for adding, enabling, refreshing, or dropping policies, policy groups, or application contexts. You need to specify the table, view, or synonym to which you are adding a policy, as well as the data pertinent to that policy, such as the policy name. Such data also includes names for the policy group and the function implementing the policy. You can also specify the types of statements the policy controls (SELECT, INSERT, UPDATE, DELETE, CREATE INDEX, or ALTER INDEX).
    for more you can refer to
    http://download-west.oracle.com/docs/cd/B19306_01/network.102/b14266/apdvcntx.htm

Maybe you are looking for

  • Does any one know how to arrange songs by location in itunes lybrary?

    I've ripped more than 100 CDs in different folder in my computer. After installing itunes, every songs is added to the library. But when I want to transpher some songs located in a specific folder, I can not find how? They only arrange by names, or a

  • How to clear items / cache in Apex 4.2

    Can someone explain how clearing cache or session state processes are supposed to work in Apex 4.2? I have an application that allows the user to look up records by last name or by social security number A look up by SSN is one to one and takes the u

  • The ringtone option does not appear in itunes

    have the iphone 4... have the app to change songs into ringtones. when I look on the itunes home page when I sync my iphone it does not have the option for ringtones on the left side fo the screen.

  • Connection between data services and BWA

    Hi, I want to make a connection between Data Services 3.2 and BWA. Since we use RFC connection in between in order to have them talk with eachother but i wonder if there is any documentation that describes the RFC connection and configuration require

  • Order item authorization object

    Hi all I am working with service orders in CRM 4.0. When I create a service order with several items, each of these items is assigned to a different user, so that he can solve it. I would like to know if there is a standard way to allow users editing