Sub queries and Triggers

Hey everybody, 
I'm having this problem creating this trigger..
This errors keeps popping up
"Only one expression can be specified in the select list when the subquery is not introduced with EXISTS"
The code is intended to send a message to the seller when the bid is at 95% and the message displays that customer information..
I've tried using EXIST but i'm not sure of the correct syntax to use that 
Can anyone help?
Here is my code:
CREATE TRIGGER msgBID ON BID
FOR INSERT, UPDATE
AS
DECLARE @Price INT
DECLARE @MSG varchar(max)
DECLARE @AskingPrice INT
BEGIN
SET @PRICE=(SELECT PRICE FROM INSERTED)
SET @AskingPrice=(SELECT Asking_Price FROM item, INSERTED WHERE ITEM.ITEMnum=INSERTED.ITEMnum)
IF
@Price <=@AskingPrice *.95
   SET @MSG=(SELECT Inserted.ITEMnum, ITEM.Name, Item.Description, F_Name, L_Name,
Customer.CID FROM ITEM, CUSTOMER, Inserted
   WHERE Inserted.ITEMnum=Item.ITEMnum and Customer.CID=Item.CID and Inserted.CID=Customer.CID
PRINT
@MSG
END

Issue is in when you want to return the message. 
You need to concatenate the values to show up as message. Next, what if there are multiple values changed, what do you want to show as output? Please clarify. 
You can use
STUFF to concatenate multiple outputs while information that you want to show the user they are also combined as single output. 
IF @Price <=@AskingPrice *.95
   SET @MSG=(SELECT 'Item Number: ' + CONVERT(VARCHAR(30), Inserted.ITEMnum) + ' - Item Name: ' + ITEM.Name + ' - ' + ' - Item Desc: ' + Item.Description + ' - First name: ' + F_Name + ' - Last Name: ' + L_Name
+ ' Customer ID: ' + CONVERT(VARCHAR(20), Customer.CID)
FROM 
dbo.Inserted
INNER JOIN dbo.CUSTOMER ON Customer.CID=Item.CID and Inserted.CID=Customer.CID
INNER JOIN dbo.ITEM ON Inserted.ITEMnum=Item.ITEMnum
Also, please try to use
JOIN
Best Wishes, Arbi; Please vote if you find this posting was helpful or Mark it as answered.

Similar Messages

  • Two similar queries and different result.

    Hi! I have a problem and
    with
    sc as (select * from nc_objects where object_type_id = 9122942307013185081 and project_id=9062345122013900768),
    cid as (select sccid.value AS CIRCUIT_ID,sc.description AS DESCRIPTION
    from sc, nc_params sccid
    where sccid.object_id = sc.object_id and sccid.attr_id = 9122948792013185590),
    caloc as ( select
    (*select value from nc_params sccid where sccid.object_id = sc.object_id and sccid.attr_id = 9122948792013185590*) as CIRCUIT_ID,
    (select sl.name from nc_objects sl join nc_references scr on sl.object_id = scr.reference
    where scr.attr_id = 3090562190013347600 and scr.object_id = sc.object_id ) as ALOCATION
    from sc),
    cbloc as ( select
    (select value from nc_params sccid where sccid.object_id = sc.object_id and sccid.attr_id = 9122948792013185590) as CIRCUIT_ID,
    (select sl.name from nc_objects sl join nc_references scr on sl.object_id = scr.reference
    where scr.attr_id = 3090562190013347601 and scr.object_id = sc.object_id ) as BLOCATION
    from sc)
    select cid.CIRCUIT_ID,cid.DESCRIPTION,ALOCATION,BLOCATION from (
    cid
    join caloc on cid.CIRCUIT_ID = caloc.CIRCUIT_ID and ALOCATION is not null
    join cbloc on cid.CIRCUIT_ID = cbloc.CIRCUIT_ID and BLOCATION is not null
    it` returns and`s all ok!
    ID desc aloc bloc
    101     TEST1     AHAS     AGUS
    102     TEST2     AKRE     AMJY
    103     TEST3     AMJS     ASSE
    109     TEST9     BAIA     AKIB
    5     (null)     WELA AGUS
    We have "sc as (select * from nc_objects where object_type_id = 9122942307013185081 and project_id=9062345122013900768)"
    and identical subquery on caloc and cbloc
    "select value from nc_params sccid where sccid.object_id = sc.object_id and sccid.attr_id = 9122948792013185590"
    If i change query on
    with
    sc as (select * from nc_objects where object_type_id = 9122942307013185081 and project_id=9062345122013900768),
    cid as (select sccid.value AS CIRCUIT_ID,sc.description AS DESCRIPTION
    from sc, nc_params sccid
    where sccid.object_id = sc.object_id and sccid.attr_id = 9122948792013185590),
    caloc as ( select
    *(select CIRCUIT_ID from cid) as CIRCUIT_ID,*
    (select sl.name from nc_objects sl join nc_references scr on sl.object_id = scr.reference
    where scr.attr_id = 3090562190013347600 and scr.object_id = sc.object_id ) as ALOCATION
    from sc),
    cbloc as ( select
    (select value from nc_params sccid where sccid.object_id = sc.object_id and sccid.attr_id = 9122948792013185590) as CIRCUIT_ID,
    (select sl.name from nc_objects sl join nc_references scr on sl.object_id = scr.reference
    where scr.attr_id = 3090562190013347601 and scr.object_id = sc.object_id ) as BLOCATION
    from sc)
    select cid.CIRCUIT_ID,cid.DESCRIPTION,ALOCATION,BLOCATION from (
    cid
    join caloc on cid.CIRCUIT_ID = caloc.CIRCUIT_ID and ALOCATION is not null
    join cbloc on cid.CIRCUIT_ID = cbloc.CIRCUIT_ID and BLOCATION is not null
    query result will be:
    ORA-01427: single-row subquery returns more than one row
    01427. 00000 - "single-row subquery returns more than one row"
    *Cause:   
    *Action:
    Can you explain why so ?
    Edited by: user12031606 on 07.05.2010 2:31
    Edited by: user12031606 on 07.05.2010 2:32

    Hi,
    Welcome to the forum!
    Whenever you post code, format it to show the extent of sub-queries, and the clauses in each one.
    Type these 6 characters:
    \(all small letters, inside curly brackets) before and after each section of formatted test; if you don't, this site will compress the spaces.
    It also helps it you reduce your query as much as possible.  For example, I think you're only asking about the sub-query called caloc, so just post caloc as if that were the entire query:select     ( select CIRCUIT_ID
         from cid
         )                as CIRCUIT_ID,
         ( select sl.name
         from nc_objects          sl
         join nc_references      scr on sl.object_id = scr.reference
         where scr.attr_id      = 3090562190013347600
         and scr.object_id      = sc.object_id
         )                as ALOCATION
    from sc
    This makes it much cleared that the query will produce 2 columns, called circuit_id and alocation.
    Compare the query above with the query below:SELECT     object_id,
         'Okay'
    FROM     sc
    The basic structure is the same: both queries produce two columns, and both queries produce one row of output for every row that is in the sc table.
    The only difference is the two items in the SELECT clause.
    The second query has a column from the table as its first column, and a literal for its second column; those are just two of the kinds of things you can have in a SELECT clause.  another thing you can have there is a +Scalar Sub-Query+ , a complete query enclosed in parentheses that produces exactly one column and at most one row.   If a scalar sub-query produces more than one row, then you get the run-time error: "ORA-01427: single-row subquery returns more than one row", as you did.
    A scalar sub-query always takes the place of a single value: "scalar" means "having only one value".  In the first example above, the main query is supposed to produce one row of output for every row in sc.  How can it do that if some of the columns themselves contain multiple rows?
    I don't know what your tables are like, or what output yu want to get from thiose tables.
    If you'd like help getting certain results from your tables, then post CREATE TABLE and INSERT statements for a little sample data, and the resutls you want to get from that sample data.  A scalar sub-query may help getting those results, or it may not.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • [8i] Question on hints when there are sub-queries / in-line views

    I've noticed that when I query my database, it seems to default to the RBO rather than the CBO. I've been troubleshooting a huge query that takes a good half an hour to run... First, when I saw it was using the RBO, I added the /*+ CHOOSE */ hint (to my top-level SELECT), but that didn't help much. So, I decided to go through all the sub-queries / in-line views. One of my sub-queries, with no hint, takes 2.5 min. to run. I added the /*+ CHOOSE */ hint to it, and it only took 20 seconds.
    My question is, if I add a hint to the top-level SELECT, does it get applied to every sub-query, or do I need to put that hint in every sub-query as well?

    I just tested this out... I ran a portion of my query with a couple of sub-queries, and the first time, I just put the CHOOSE hint in my top level SELECT statement. The second time, I put it in both the top level and in the SELECT statement of one of the sub-queries. The explain plans are too long to post, but these are the statistics:
    1st run (only 1 hint):
    Statistics
              0  recursive calls
           2345  db block gets
         885019  consistent gets
            681  physical reads
              0  redo size
         185226  bytes sent via SQL*Net to client
          11371  bytes received via SQL*Net from client
            160  SQL*Net roundtrips to/from client
              0  sorts (memory)
              1  sorts (disk)
           2371  rows processed
    timing for: query_timer
    Elapsed: 00:00:29.092nd run: (2 hints)
    Statistics
             14  recursive calls
           2345  db block gets
         885035  consistent gets
            620  physical reads
              0  redo size
         185226  bytes sent via SQL*Net to client
          11371  bytes received via SQL*Net from client
            160  SQL*Net roundtrips to/from client
           4498  sorts (memory)
              1  sorts (disk)
           2371  rows processed
    timing for: query_timer
    Elapsed: 00:00:56.03It looks to me like the first one ran more efficiently. Can someone explain this to me? I figured that putting hints in the sub-queries would, at worst, do nothing, and at best, improve the performance, but it looks like the opposite happened.
    Edited by: user11033437 on Aug 12, 2010 11:17 AM (fixed some info/copy paste error)

  • Disco Plus and Sub-queries in conditions

    Hi,
    I have a strange behaviour for a report using a sub-query in the condition:
    in Desktop Edition and Viewer it works just fine, in Plus no data is returned.
    I am using Discoverer 9.0.2.
    The condition was created from the Desktop using an existing datasheet, both data sheets using the same parameter.
    I examined the SQL code from Plus and the statement returns data and the sheet with the sub-query also returns data - nevertheless the report doesn't return any data.
    As far as I know you cannot create or modify sub-queries in conditions with PLus - but at least the report should work?! Does anyone know where the problem could be?
    Thank you very much in advance!
    Alex

    Trying to create a sub-query in discoverer...
    Using Desktop (9.04 and 10.1.2), the option "Create Sub-Query" is not available in the condition values. Feel like I'm missing something - has anyone come across this before?
    I assume sub-queries should be possible/supported in Plus 10.1.2 (although it's not in the user guide). If so, the Create Sub-Query option is not available like in Desktop. If not, why not - seeing as it's basic sql commonly used in reporting?
    Thanks!

  • In which sequence are queries and sub-queries executed by the SQL Engine

    In which sequence are queries and sub-queries executed by the SQL Engine?
    Which is correct ?
    a. primary query -> sub query -> sub sub query and so on
    b. sub sub query -> sub query -> prime query
    c. the whole query is interpreted at one time
    d. there is no fixed sequence of interpretation, the query parser takes a decision on the fly

    In which sequence are queries and sub-queries executed by the SQL Engine?
    Which is correct ?
    a. primary query -> sub query -> sub sub query and so on
    b. sub sub query -> sub query -> prime query
    c. the whole query is interpreted at one time
    d. there is no fixed sequence of interpretation, the query parser takes a decision on the fly
    Hi, below may help you understanding simple subquery & correlated subquery
    refer :
    http://sqlmag.com/t-sql/t-sql-starters-simple-and-correlated-subqueries
    a) if it is correlated subquery
     A correlated subquery is one that depends on a value in the outer query. In programming terms, you pass the subroutine an argument, then the subroutine evaluates the query and returns a result. You move on to the next record and repeat the process. The
    net effect is that the subquery runs once for every row in the main query; this situation is inefficient.
                                  A possible alternative is to rewrite the correlated subquery as a join. However,
    some situations require a subquery. Eg- IN(with outer table refernce)
    so  main query -> subquery
    b) if it is simple subquery
    A subquery is a query that SQL Server must evaluate before it can process the main query, Eg- IN(with out outer table refernce)
    so subquery-> main query
    c) correlated query interpreted row by row with subquery, while subquery is interpreted at one time(outer table and inner table)
    d) in most case it depends on the whether it is correlated subquery or simple subquery
    Thanks
    Saravana Kumar C

  • Function and triggers and procedures

    sorry to asking this question,
    In oracle. we use the function and triggers and procedure.
    for eg:
    if we wrote an trigger for a table. it fires at a time manipulating table. (database contains table contains datas and database also contains triggers likewise function,procedure).
    but my questions?: is
    In my database I kept only tables. no triggers,no function,no procedures. and
    i dont want to kept this triggers, function, procedures in database  Instead of i want to kept this triggers, function, procedures in business logic layers(middle tier)
    is it possible? .
    if yes means, how to write or where to write? please help me, or else send the guidance documents or blog releated to it.

    Subu123,
    the +1 related to Would be great if you can take step back and see the implementation from another angle. First see why do you need DB trigger/function etc.Then check whether it is possible to implement the functionality using ADF BC + feasibility study between 2 approaches(I didn't mean to invoke DB objects from business components, instead checking the feasibility of implement the same functionality in your EntityObj/ViewObj/Service calls )Before making a decision for or against holding fuctions, triggers and procedures in the DB, you have to get the whole picture.
    Think about a trigger outside the DB. What could this be and why or for what is it used?
    All the answers are pointing to 'lets keep them in the DB'. Now there are situation where you don't have a DB or are not allows to use it. Still there can be triggers, only they are implemented in a different way.
    The same can be said for procedures and functions.
    So you have to think about the whole problem and how each sub problem you have to solve work together to resolve the whole problem.
    I'm personally tend to keep the business logic the the DB if the business logic is already there (e.g. I have to migrate an old forms app).
    If I design a new app I tend to keep the logic in java. Only sequences (for generating ids) and some other stuff which is purely db related like cleaning up tables I keep in the DB.
    Timo

  • IN clause with ORDER BY clause in sub-queries

    Hello,
    We generate dynamic queries with the following statement pattern (could be many union/intersect sub-queries):
    select my_col
    from my_table
    where my_col IN
    select table_2.my_col , x_col from table_2 where x_col > 10
    UNION
    select table_3.my_col , y_col from table_3 where y_col > 20
    INTERSECT
    select table_4.my_col , z_col from table_4 where z_col is between 30 and 50
    I know that I can do just the sub-queries w/ an ORDER BY clause as follows (as long as the 2nd parameter in the select stmts are of the same type):
    select table_2.my_col , x_col from table_2 where x_col > 10
    UNION
    select table_3.my_col , y_col from table_3 where y_col > 20
    INTERSECT
    select table_4.my_col , z_col from table_4 where z_col is between 30 and 50
    order by 2 desc
    But my questions are:
    1. What is (if there is) the syntax that will ensure that the result set order will be that of the ordering of the sub-queries?
    Or does my SQL stmt have to have syntactically (but not semantically) change to achieve this?
    Thanks,
    Jim

    Randolf Geist wrote:
    just a minor doubt - I think it is not officially supported to have separate ORDER BYs in a compound query with set operators (e.g. UNION / UNION ALL subsets). Of course one could use inline views with NO_MERGE + NO_ELIMINATE_OBY hints, but I think the only officially supported approach is to use a single, final ORDER BY (that needs to use positional notation as far as I remember).
    Randolf,
    You're right, of course, about the separate "order by" clauses.
    Interestingly the following type of thing does work though (in 10.2.0.3, at least):
    with v1 as (
        select * from t1 where col1 = 'ABC' order by col2
    v2 as (
        select * from t1 where col1 = 'DEF' order by col2
    select * from v1
    union all
    select * from v2
    ;A quick check the execution plan suggsts that Oracle appears to be convering this to the following - even though its technically not acceptable in normal circumstances:
    select * from t1 where col1 = 'ABC' order by col2
    union all
    select * from t1 where col1 = 'DEF' order by col2
    ;Regards
    Jonathan Lewis
    http://jonathanlewis.wordpress.com
    http://www.jlcomp.demon.co.uk
    To post code, statspack/AWR report, execution plans or trace files, start and end the section with the tag {noformat}{noformat} (lowercase, curly brackets, no spaces) so that the text appears in fixed format.
    "Science is more than a body of knowledge; it is a way of thinking"
    Carl Sagan                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • With clause vs sub-queries

    db and dev 10g rel2 , hi all,
    i am trying to learn the "WITH CLAUSE" , and i do not see any difference between using it and using sub-queries .
    when i searched for this , i found that the with clause is used when You need to reference the subquery block multiple places in the query by specifying the query name , but i can not imagine an example for doing so .
    if you could provide me with an example please ? and telling me about another situations in which i could need using the "with clause" if any ?
    thanks

    >
    db and dev 10g rel2 , hi all,
    i am trying to learn the "WITH CLAUSE" , and i do not see any difference between using it and using sub-queries .
    when i searched for this , i found that the with clause is used when You need to reference the subquery block multiple places in the query by specifying the query name , but i can not imagine an example for doing so .
    if you could provide me with an example please ? and telling me about another situations in which i could need using the "with clause" if any ?
    >
    It isn't just about referencing a subquery multiple times. There are other advantages to using 'common table expressions'/'subquery factoring' also.
    Take a look at the example below. It first defines 'dept_costs' as a query block, then defines 'avg_cost' as a new query block and it references the first query block.
    Then the actual query references both query blocks just as if they are tables. And, in fact, in some circumstances Oracle will actually materialize them AS temporary tables.
    Look at how easy it is to understand the entire statement. You can focus first on the 'dept_costs' query block WITHOUT having to look at anything else. That is because the query block is self-contained; you are defining a result set. There is no 'join' or connection to any other part of the statement.
    It is easy for a developer, and for Oracle, to understand what is needed for that one piece.
    Next you can focus entirely on the 'avg_cost' query block. Since it uses the first query block just as if it were a table you can treat it as a table. That means you do NOT even need to look at the first query block to understand what the second query block is doing.
    Same with the actual query. You can analyze it by treating the two query blocks just as if they were other tables.
    Even better you can test the first query block by itself in sql*plus or other tool to confirm that it works and you can create an execution plan for it to make sure it will use an appropriate index. You can also then test the first and second query blocks together to make sure THEY have a proper execution plan.
    Then when you test then entire statement you already know that the query blocks work correctly.
    Try to do THAT with a query that uses nested sub-queries.
    Sure - you could write a set of nested sub-queries to accomplish the same thing (Oracle will sometimes rewrite your query that way itself) but it becomes one big query and the individual pieces are not nearly as easy to see, analyze or understand.
    It can be difficult if not impossible to extract a nested query in order to test it even to just try to get the syntax working. And when you do extract it you will often be testing something that isn't quite exactly the same as when i t was nested.
    So: easier to understand, easier to write and test (especially for new developers) as well as easier to use multiple times without having to duplicate it.
    >
    subquery_factoring_clause
    The WITH query_name clause lets you assign a name to a subquery block. You can then reference the subquery block multiple places in the query by specifying the query name. Oracle Database optimizes the query by treating the query name as either an inline view or as a temporary table.
    >
    The SQL Language doc has an example.
    http://docs.oracle.com/cd/B28359_01/server.111/b28286/statements_10002.htm#i2129904
    >
    Subquery Factoring: Example The following statement creates the query names dept_costs and avg_cost for the initial query block containing a join, and then uses the query names in the body of the main query.
    WITH
    dept_costs AS (
    SELECT department_name, SUM(salary) dept_total
    FROM employees e, departments d
    WHERE e.department_id = d.department_id
    GROUP BY department_name),
    avg_cost AS (
    SELECT SUM(dept_total)/COUNT(*) avg
    FROM dept_costs)
    SELECT * FROM dept_costs
    WHERE dept_total >
    (SELECT avg FROM avg_cost)
    ORDER BY department_name;
    DEPARTMENT_NAME DEPT_TOTAL
    Sales 313800
    Shipping 156400

  • SELECT, hierarchical queries and JOIN

    Hi everyone,
    I have a small SELECT statement but I can't find an easy solution.
    Look at this situation:
    drop table departments;
    CREATE TABLE departments
      dpt_id NUMBER(10) UNIQUE,
      dpt_name VARCHAR2(100),
      dpt_parent_id NUMBER(10)
    TRUNCATE table departments;
    INSERT INTO departments VALUES(1, 'Company', null);
    INSERT INTO departments VALUES(2, 'HR', 1);
    INSERT INTO departments VALUES(3, 'SALES', 1);
    INSERT INTO departments VALUES(4, 'IT', 1);
    INSERT INTO departments VALUES(222, 'Helpdesk', 4);
    INSERT INTO departments VALUES(223, 'French Speaking', 222);
    INSERT INTO departments VALUES(224, 'Another level', 223);
    INSERT INTO departments VALUES(5, 'LEGAL', 1);
    INSERT INTO departments VALUES(66, 'Recruitment', 2);
    INSERT INTO departments VALUES(33, 'Logistics', 2);
    INSERT INTO departments VALUES(39, 'Fleet management', 33);
    INSERT INTO departments VALUES(31, 'Local Sales', 3);
    INSERT INTO departments VALUES(60, 'European Sales', 3);
    INSERT INTO departments VALUES(61, 'Germany', 60);
    INSERT INTO departments VALUES(62, 'France', 60);
    INSERT INTO departments VALUES(620, 'Paris', 62);
    INSERT INTO departments VALUES(621, 'Marseilles', 62);
    INSERT INTO departments VALUES(38, 'American Sales', 3);
    INSERT INTO departments VALUES(34, 'Asian Sales', 3);
    CREATE table persons
      person_id NUMBER(10) UNIQUE,
      person_name VARCHAR2(100),
      person_dpt_id NUMBER(10)
    truncate table persons;
    INSERT INTO persons VALUES(1, 'Jim', 2);
    INSERT INTO persons VALUES(2, 'Jack', 621);
    INSERT INTO persons VALUES(3, 'John', 620);
    INSERT INTO persons VALUES(4, 'John', 224);
    INSERT INTO persons VALUES(5, 'Fred', 61);It's a simple hierachy like the one we can find in HR schema. The link between an department and its parent is with parent id. THe following statement build the whole tree:
    SELECT dpt_id, level, LPAD(' ', LEVEL-1)|| dpt_name
      FROM departments
    START WITH dpt_parent_id IS NULL
    CONNECT BY dpt_parent_id = PRIOR dpt_id;As you can see in the script above, I have a few people assigned to these departments. It's also a classic situtation...
    I would like to have something like this:
    WITH temp AS
      SELECT dpt_id, dpt_name, SYS_CONNECT_BY_PATH(dpt_name, '#') as full_path
        FROM departments
       START WITH dpt_parent_id IS NULL
    CONNECT BY dpt_parent_id = PRIOR dpt_id
    SELECT p.person_name, d.dpt_name, --d.full_path,
           regexp_substr(d.full_path, '[^#]+', 1, 2, 'i') as t1,
           regexp_substr(d.full_path, '[^#]+', 1, 3, 'i') as t2,
           regexp_substr(d.full_path, '[^#]+', 1, 4, 'i') as t3,
           regexp_substr(d.full_path, '[^#]+', 1, 5, 'i') as t4
      FROM persons p
      JOIN temp d ON d.dpt_id = p.person_dpt_id;This is the exact output I want, but I wonder... Is it possible to do it without the factored sub-query? It's nice and works fine but I had to precompute the whole path to split it again. I mean, this should be possible in one step. Any suggestion?
    I'm using Oracle 10g
    Thanks,

    Hi,
    user13117585 wrote:
    ... But sometimes, I just find the statements difficult for what they do. For example, my previous one. I have a person, and I want to see his department and the path in the tree.Actually, you want more than that; you want to parse the path, and display each #-delimited part in a separate column. If you didn't want that, then you could do away with the 4 REGEXP_SUBSTR calls, like this:
    WITH temp AS
      SELECT dpt_id, dpt_name
      ,       SUBSTR ( REPLACE ( SYS_CONNECT_BY_PATH ( RPAD (dpt_name, 15)     -- Using 15 just for demo
               , 16
               )     as full_path
        FROM departments
       START WITH dpt_parent_id IS NULL
    CONNECT BY dpt_parent_id = PRIOR dpt_id
    SELECT p.person_name, d.dpt_name, d.full_path
      FROM persons p
      JOIN temp d ON d.dpt_id = p.person_dpt_id;Output:
    PERSON_N DPT_NAME      FULL_PATH
    Jim      HR            HR
    Fred     Germany       SALES          European Sales Germany
    John     Paris         SALES          European Sales France         Paris
    Jack     Marseilles    SALES          European Sales France         Marseilles
    John     Another level IT             Helpdesk       French SpeakingAnother levelAs you can see, full_path is one giant column, but it's formatted to look like 4 separate columns, forresponding to your original t1, t2, t3 and t4. I limited the output to 15 characters, just for debugging and posting purposes. You can use any number of characters you like.
    It's too complex for this simple thing.It would be nice if there was something simpler that did exactly what you wanted, but I'm not sure it's reasonable to expect it in every case. I asked a lot of questions in my first message, but I'm not sure you've tried to answer any of them, so I'm not sure why you're unhappy with the query you posted. I can think of lots of ways to change the query, but I have no way of telling if you would like them any better than what you already have.
    And hopefully, I know where to start in the hierarchy and I know where to stop. If I had to show all the levels and have one column by level dynamically, I'd be stuck. Sorry, I don't understand this part.
    Are you saying that it seems inefficient to generate the entire tree, when perhaps few of the nodes will have have matches in the persons table? If so, you can invert the whole query. Instead of doing the CONNECT BY first and then joining, do the join first and then the CONNECT BY. Instead of doing a top-down CONNECT BY, where you start with the parentless nodes (whether or not you'll ultimately need them) and then find their descendants, do a bottom-up CONNECT BY, where you start with the nodes you know you'll need, and then find their ancestors.
    I just find it difficult for such a simple need. Again, there are lots of things that could be done. If you won't say what you want, that makes it hard for me to tell you how to get it. All that I've picked up for sure is that you don't like doing a sub-query. That's unfortunate, because sub-queries are so basic. They have very important been since Oracle 8.1, and they don't seem to be going away. Quite the opposite, in fact. You need sub-queries for all kinds of things, not just CONNECT BY. To give just a couple of examples, they're the only thing that make analytic functions really useful, and they simplfy chasm traps (basically, multiple 1-to-many relationships on the same table) considerably. I'm sorry if you don't lke sub-queries, but I don't see how you can work in this field and not use them.
    Edited by: Frank Kulash on Nov 15, 2011 3:18 PM
    Revised query

  • Sub Queries VS  Variables in the Query

    #1
    for i in ( select a.name,b.price,a.date from
    list a, sales b
    where a.header_id=b.header_id
    and b.date_key= (select date_key from date_tab
    where date_field=trunc(sydate))
    loop
    end loop.
    #2
    select date_key into v_date_key from date_tab where date_field=trunc(sydate);
    for i in ( select a.name,b.price,a.date from
    list a, sales b
    where a.header_id=b.header_id
    and b.date_key= v_date_key)
    loop
    end loop.
    Please advice me , using the sub queries(#1) or substution variable (#2) in the condition part will improve the performance of the query.
    Thanks

    Most likely, there won't be a difference in performance.
    Justin
    Distributed Database Consulting, Inc.
    http://www.ddbcinc.com/askDDBC

  • Sub queries

    i have a longish query which runs correctly in Oracle 8i Lite thro SQL Plus but does not run when using JDBC.
    The query has multiple subqueries and it looks like
    delete from node_initial_values d where d.node_id in (select c.node_id from node_master c where c.node_id=d.node_id and c.node_id in (select e.node_id from network_design e where c.node_id=e.node_id and e.network_id in (select b.network_id from network_master b where e.network_id=b.network_id and b.network_id in (select g.network_id from output_network_scenario g where g.network_id=b.network_id and g.output_network_master_id in (select a.output_network_master_id from output_network_master a where a.output_name= 'network three')))));
    assume all the tables exist with correct data. the above query works perfectly well in SQL*plus but when i use
    the following code i get an error
    PreparedStatement deleteNodeInitialValuesPst=getConn.prepareStatement("delete from node_initial_values d where .... a where a.output_name= ?)))))");
    deleteNodeInitialValuesPst.setString(1,"network three");
    deleteNodeInitialValuesPst.executeUpdate();
    getConn.commit();
    ... rest of the code
    the error code oracle 8i lite gives is
    java.sql.SQLException: [POL-4200] bad action for transaction operation
    would really appreciate any help in this regard...
    specifically can anyone tell me if prepared statement is the correct function to use here...
    thanks

    I made the following changes:
    changes to the code, new code mentioned below
    changed the database to oracle 8i enterprise edition running on NT.
    new code now is
    // connetion parameter and other code here
    String deleteNodeInitialValuesStr=
    "delete from node_initial_values d where d.node_id in (select c.node_id from node_master c where c.node_id=d.node_id and c.node_id in (select e.node_id from network_design e where c.node_id=e.node_id and e.network_id in (select b.network_id from network_master b where e.network_id=b.network_id and b.network_id in (select g.network_id from output_network_scenario g where g.network_id=b.network_id and g.output_network_master_id in (select a.output_network_master_id from output_network_master a where a.output_name='"+nextElementStr+"')))))";
    Statement deleteNodeInitialValuesSt=getConn.createStatement();
              deleteNodeInitialValuesSt.executeQuery(deleteNodeInitialValuesStr);
    getConn.commit();
    } // end try
    catch(SQLException ex) {
         while(ex !=null){
    out.println("Java SQL Exception: " + ex.getMessage()+"<br>");
    out.println("Vendor error code: " + ex.getErrorCode()+ "<br>");
    out.println("SQL State: " + ex.getSQLState() + "<br>");
    ex=ex.getNextException();
    } // end while
    } // end catch
    // more code here
    the output i get is
    Java SQL Exception: 202
    Vendor error code: 0
    SQL State: null
    I turned off getConn.commit(), but the error code remains the same. is there an alternative to the sub queries above. where can i get the meaning of the error codes thrown by the exception ?
    thanks

  • How can I create "Sub Queries" in a select statement?

    Hi all,
    I need to create reports, which are not based on a single table but on several "sub-queries".
    This would be the code, but I don't know how to solve that problem...
    SELECT OGBI.*
    FROM
    (((select "OSSRALL"."FORECAST_OWNER", sum
    ("OSSRALL"."TOTAL_OPPORTUNITY_AMOUNT")
    from "#OWNER#"."OSSRALL" "OSSRALL",
    "#OWNER#"."TEAM_MAIN" "TEAM_MAIN",
    "#OWNER#"."MA_MAIN" "MA_MAIN"
    group by "OSSRALL"."FORECAST_OWNER")OGBI.APPSME1)
    where "OSSRALL"."OPP_CLASS" = (EX_OTHERS)),
    -- more are following
    "#OWNER#"."OSSRALL" "OSSRALL",
    "#OWNER#"."TEAM_MAIN" "TEAM_MAIN",
    "#OWNER#"."MA_MAIN" "MA_MAIN"
    WHERE
    ("MA_MAIN"."MA_NAME"||', '||"MA_MAIN"."MA_FIRST_NAME"||' Mr'
    like "OSSRALL"."FORECAST_OWNER" or
    "MA_MAIN"."MA_NAME"||', '||"MA_MAIN"."MA_FIRST_NAME"||' Mrs'
    like "OSSRALL"."FORECAST_OWNER" or
    "MA_MAIN"."MA_NAME"||', '||"MA_MAIN"."MA_FIRST_NAME"
    like "OSSRALL"."FORECAST_OWNER") and
    ("OSSRALL"."SALES_GROUP"="TEAM_MAIN"."NAME") and
    ("MA_MAIN"."MA_ID"=:P17_VB1)
    thx a lot for your help.
    kind regards Jan
    Message was edited by:
    Jan Rabe

    Jan
    Please can you post the full select statement and the DDL to create the tables? Or, provide someone access to the app on the Oracle server.
    We can probably make these much more readable using table aliases and removing the owner unless you are doing this across schemas or via a wizard?
    It looks like you are missing joins in your query - is this what you mean by subqueries? It is a good idea to move the join up before the WHERE clause if you can as this makes the query easier to manage.
    Phil

  • Using Sub Queries in OBIEE

    Hi,
    I am new to the OBIEE world and was wondering how we can work with sub queries. I have the following problem.
    I have a table namely XYZ in which we have "effective date" and "Amount". In the answers section have have filter out the data for the month of 01-Nov-08 to 30-Nov-08 which shows the total cash amount for that month. Now the problem is that I need to use the same "effective date" and "Amount" to get the opening balance which is calculated by Sum(Amount) where "effective date" < 01-Nov-2008. If i try to do this I do not see any results as the data gets filtered out. Can someone please help me on this?
    Thanks

    Hi,
    In column formula put column level filter like this FILTER("Facts Revenue".Revenue USING (Time."Day Date" < date '2006-10-09'))
    Regards
    Naresh

  • Can anyone tell me WHY Oracle won't allow sub-queries in outer joins?

    Hi,
    I've recently been tasked with converting a series of InterBase dbs to Oracle.
    Many of the queries in the InterBase dbs use sub-queries in outer joins. Oracle won't countenance this (01799 - a column may not be outer-joined to a subquery).
    I can get around it using functions but WHY won't Oracle allow this?
    SQL Server allows it, InterBase allows it (I don't know about ANSI SQL) but it seems to be a common enough technique...
    I'm just curious (and also a little frustrated!).
    Thanks in advance,,,

    Hi,
    >>Oracle treat an empty string as a NULL
    Well, you same answer your question. Because it is empty
    SGMS@ORACLE10> create table tab (cod number, name varchar2(1));
    Table created.
    SGMS@ORACLE10> insert into tab values (1,'');
    1 row created.
    SGMS@ORACLE10> insert into tab values (2,' ');
    1 row created.
    SGMS@ORACLE10> commit;
    SGMS@ORACLE10> select cod,dump(name) from tab;
           COD DUMP(NAME)
             1 NULL
             2 Typ=1 Len=1: 32
    SGMS@ORACLE10> select * from tab where name is null;
           COD NAME
             1Cheers
    If you talking about language tools, for example PHP treat empty string <> of NULL values. e.g: functions like is_empty() and is_null()
    Message was edited by:
    Legatti

  • Usage of joins & sub-queries

    can anyone help me know the situation when to use the joins and sub-queries manipulating with more than one tables???? which among the two is faster normally???? because we can do same process using both these options.....

    Balasubramaniam:
    I think I can be so bold to say that, in general, joins are faster than sub-queries. But there are a lot of variables - data types, row/table sizes, indexes.
    Try it and compare, with your production data.
    Tom Best

Maybe you are looking for