Can I write merge SQL statement having count(*)?

Hi this is a followup question of my previous post. I tried to use a merge SQL statement to solve my problem but now I bump into another problem.
Now I have a table where the field I need to update is a partial PK
when using a merge SQL statement, I have to put a where clause that check if count(*) = 1 because of the PK constraint
Where can I put the count(*) = 1 clause?
Here are the details:
I have two tables TA and TB, where TA contains the fields ID, FULLNAME, TYPE and TB contains the fields ID, FIRSTNAME
I want to update the firstnames in TB to be the firstnames from TA where TB.ID = TA.ID and TA.TYPE = 'ABC'
{ID, FIRSTNAME} are PKs but for the same ID, there can be more than 1 firstname.
e.g.
TA
ID | FULLNAME | TYPE
1 Caroline T ABC
2 Mary C DEF
3 Peter J ABC
TB
ID | FIRSTNAME
1 Caroline
1 Carol
1 C,
3 Peter
I need to update TB with the new firstnames from TA where type is 'ABC' but only for those fields that have count(TB.ID) = 1
when I try to run this SQL statement
merge into TB B using TA A
on (A.ID = B.ID and A.TYPE = 'ABC')
when matched then update set B.FIRSTNAME = substr(A.FULLNAME, 1, instr(A.FULLNAME, ',') - 1)
I got this error SQL Error: ORA-00001: unique constraint (TEST.PK_TB) violated
which I believe is because I updated those fields say ID = 1, all with 'Caroline'
that means I will have to add a clause having count(TB.ID) = 1
How would you do it?
Server is Oracle 11g
Thank you!

Hi,
One way is to join ta and tb in the USING clause, and eliminate the duplicates there.
MERGE INTO     tb     dst
USING   (
         SELECT    ta.id
         ,           REGEXP_SUBSTR ( MIN (ta.fullname)
                                , '^[^,]*'
                        )     AS firstname
         FROM      ta
         JOIN      tb  ON  ta.id     = tb.id
         WHERE     ta.type      = 'ABC'
         GROUP BY  ta.id
         HAVING    COUNT (*)     = 1
     )                   src
ON     (scr.id      = dst.id)
WHEN MATCHED THEN UPDATE
SET     dst.firstname     = src.firstname
;If you'd care to post CREATE TABLE and INSERT statements for your sample data, then I could test this.
I used REGEXP_SUBST instead of SUBSTR and INSTR to find the firstname, because I find it a little cleaner, and becuase it returns something even when there is no ',' in fullname, which I'm guessing is what you really want. (None of the fullnames in your sample data have ','s.) You could use SUBSTR and INSTR instead.

Similar Messages

  • How can I write a SQL statement which checks if a table exists?

    How can I write a SQL statement which tells me whether a table exists?

    execute an sql query: select * from <tablename>
    catch the exception n check whether the erroe code
    matches the one that occurs for table doesn't exist
    that's itHow is your answer any different from the one given in the first reply?
    It isn't.
    As WorkForFood says DatabaseMetaData has a bunch of methods for getting information about tables but this is more useful when you don't know the names of any of the tables.. it sounds like you do so I would concur SELECT from table is probably the quickest way to go. If it helps the Xopen error should be either S1000 or 42S01 (I think) but I would try and see if there is a specific vendor code for table not found/not exists error and check for that.

  • How can i use one SQL statement to solve problem?

    How can i use one SQL statement to solve the question below?
    For a Table named A, there is a column named F(char type).
    Now select all the records where F like '%00' and update their F value to '%01'
    Just one SQL statement.Do not use PL/SQL block.
    How to do that?
    Thanks.

    What is the data volume for this table?
    Do you expect lots of rows to have '%00' as their value?
    Following two statements come to mind. Other experts would be able to provide better alternatives:
    If you have index on SUBSTR(f, 2):
    UPDATE A
    SET    f = SUBSTR(f,
                      1,
                      length(f) - 2) || '01'
    WHERE  substr(f,
                  -2) = '00';If most of the rows have pattern '%00':
    UPDATE A
    SET    f = SUBSTR(f,
                      1,
                      length(f) - 2) ||
               DECODE(SUBSTR(f,
                             -2),
                      '00',
                      '01',
                      SUBSTR(f,
                             -2));

  • Can we write an IIF statement in Designer??

    Hi dears,
    Can we write an IIF statement in Designer when we connect to the SAP BI 7.0 InfoCube?
    I try to add a new dimension object to my universe design by using IIF statement.
    At the below you can find my simple IIF statement.
    <EXPRESSION>IIF([0FISCPER3].[LEVEL01].[[40FISCPER3]].[Value]='January',1,0)</EXPRESSION>
    Is there anything wrong with syntax or smt??
    my Business Objects env is BOXI 3.2
    thanks a lot,
    Omer

    Hi,
    this one includes samples:
    https://www.sdn.sap.com/irj/scn/go/portal/prtroot/docs/library/uuid/c0a45246-ce76-2b10-e688-f5c8206203eb
    Ingo

  • Q: how can i write PL/SQL block to check prerequisite?

    Hello...
    I designed an application using sql*plus statment for creating database and developer for creating forms, for on-line registration system for universties,
    so I need to teach me how can I write pl/sql block to check the prerequisite, taken courses, and complete hours for the students who wants register the courses via Internet.
    thanks alot in advance
    kindly send the answers a.s.a.p

    please repost this in the SQL & PL/SQL forum
    thanks - OTN

  • How to write the sql statement of my finder function in cmp?

    hi,
    I create a cmp ejb from table INFOCOLUMN,and I create a my finder function ,which sql statement is :
    select * from INFOCOLUMN WHERE employee_id=id
    employee_id is a column of the table,and id is the finder function parameter.
    The error is : invalid column name
    So,how to write the sql statement.
    Thanks .

    Mole-
    Bind variables are of the form $1, $2, etc., so your query stmt should look like:
    select * from INFOCOLUMN WHERE employee_id=$1
    -Jon

  • XML Publisher - can we specify multiple SQL statements in the report?

    Hi there,
    can we specify multiple SQL statements in the report with XML Publisher?
    Regards,
    Liviu

    Could we eventually generate with the Wizards available in XML Publisher desktop 5.6.2 an xml file with a structure like the one given below? The reason is to facilitate creation of the two rowsets. Thanks, Liviu.
    <?xml version="1.0" encoding="UTF-8"?>
    <DATA>
         <ROWSET2>
              <ROW2>
                   <FIELD1>Query1</FIELD1>
                   <FIELD2>field2</FIELD2>
                   <FIELD3>field3</FIELD3>
              </ROW2>
         </ROWSET2>
         <ROWSET>
              <ROW>
                   <FIELD1>Query2</FIELD1>
                   <FIELD2>field2</FIELD2>
                   <FIELD3>field3</FIELD3>
              </ROW>
         </ROWSET>
    </DATA>

  • Why below MERGE sql statement is throwing error  on 10g?

    Version: Ora 10g R2
    Why below MERGE sql statement is throwing error on 10g?
    SQL> merge into sess_stats
    using
    select a.name, b.value from v$statname a, v$sesstat b where a.statistic#=b.statistic# and b.sid=:sid  and (a.name like '%ga %' or a.name like '%direct temp%')
    ) curr_stats
    on (sess_stats.name=curr_stats.name)
    when matched then
         update set diff=curr_stats.value-sess_stats.value, value=curr_stats.value
    when not matched then
         insert (name, value, diff) values (curr_stats.name, curr_stats.value, null)  2    3    4    5    6    7    8  SQL> SP2-0734: unknown command beginning "on (sess_s..." - rest of line ignored.
    SQL> SP2-0734: unknown command beginning "when match..." - rest of line ignored.
    SQL>   2    3

    First of all, thank you all for your feedback!
    first, I try remove the blank lines at those two places ( before curr_stats and after on) and it works.
    then, again I try to set sqlblanklines on, and it works as well!
    Edited by: PhoenixBai on Nov 10, 2009 10:54 PM

  • Can we write the select statement on maintence view for data retreval

    Can we use the select statement on maintence view
    Regrads
    Diva

    No. U cannot write a select on maintenance view.

  • How can I execute Dynamic SQL statement in Forms?

    Hi All,
    I have to execute dynamic SQL statement from Forms
    Below statement I have to execute
    "EXECUTE IMMEDIATE v_stmt INTO v_return;".
    Googled for the same got results saying, Better use Database function or procedures to execute these Dynamic Statements but We want to execute in forms only.
    Can any one help me..
    Thanks,
    Madhu

    So in short you are trading code obfuscation for maintainability and the ability to share code between tools? If from somewhere else you need a procedure already implemented in database PL/SQL (and now ported to forms) this would mean you'd need to implement it in every other tool. In times where you might want to integrate your forms with $other_technology and putting stuff on the database is the first step to share functionality you just go the opposite way? And all that because someone is afraid that somebody might steal your source code? I am sorry to be blunt, but this is just plain stupid.
    Leaving aside that some things like Analytic Functions, Bulk processing or execute immediate are not even available in forms your software consists of how many LOC? How long does it take to bring a new developer up to speed with your source code? Imagine how long that would take for a developer who doesn't have coleagues who know their way around.
    And just so you know: I work for a ISV selling a closed-source product as well. We have 200+ customers all over the planet. We are well aware that wrapped packages can be reverse engineered. The premise is: stored procedures can be reused in every tool we have, if it makes sense to put stuff on the database by all means do it. If someone would want to reverse engineer our software I'd wish him good luck as some parts are implemented in such a hilarious complicated way I have troubles understanding them (and quite frankly I refuse to understand certain parts, but that's another story). I do work for almost 10 years for that ISV.
    In any case the possible solutions have already been mentioned: you have exec_sql, create_group_from_query and forms_ddl to execute dynamic SQL in forms whereas forms_ddl is a one way street and most certainly not the thing you need or want. Take a look at the documentation for the other 2 things.
    cheers

  • Can you use nested sql statements in jsp??

    HI, I was wondering if you can use nexted sql statements...
    example...
    <%@ page language="java" contentType="text/html" %>
    <%@ page import="java.sql.*" %>
    <%@ page import="forum.DataAccess" %>
    <%
         // Create a new instance of the DataAccess Class
              DataAccess d = new DataAccess();
         // This call the database connection method from the DataAccess Class
              d.ConnectDatabase();
         /* This gets the threads from database for the categories */
              // This is initilzing the variables
                   String threadname = null;
                   int threadid = 0;
              // This sets the sql variable to nothing
                   String sql = "";
                   String sql1 = "";
              // This sets the rs variable to null
                   ResultSet rs = null;
                   ResultSet rs1 = null;
              // This is doing a SELECT on the thread table based on the category id
                   sql += "select * from forum_threads where ft_catid = 2";
                   rs = d.SQLQuery(sql);
         /* End of categories */
         while (rs.next()){
                                       threadid = rs.getInt("ft_threadid");
                                       threadname = rs.getString("ft_threadname");
         sql1 += "select * from forum_messages where fm_catid = 2 and fm_threadid = " + threadid + "";
         rs1 = d.SQLQuery(sql1);
    %>
    THis is the error I get.....
    javax.servlet.ServletException: [Microsoft][ODBC SQL Server Driver]Connection is busy with results for another hstmt
    I know what that is.. it is because I am trying to open another result set before the first one is closed... but I need that one open cause I need to loop through the ids and run it against the second query??
    Any suggestions...

    I am not positive but it seems from your error message you will not be able to use the nested SQL. Another option would be to store the values of the ResultSet in a Vector (or Array), and then close your ResultSet and loop through the vector or array instead...
    Zac

  • Can I capture the SQL statement cuasing an error?

    I have an error log that capures SQLCODE & SQLERRM.
    Can I also capture the actual SQL statement causing the error?

    there is also format call stack, format error stack and format error backtrace.
    /* Formatted on 6/21/2011 3:45:40 PM (QP5 v5.149.1003.31008) */
    BEGIN
       FOR c IN (SELECT TO_NUMBER ('hey Im not a number') FROM DUAL)
       LOOP
          NULL;
       END LOOP;
    EXCEPTION
       WHEN OTHERS
       THEN
          DBMS_OUTPUT.PUT_LINE ('SQLCODE :' || SQLCODE);
          DBMS_OUTPUT.PUT_LINE ('SQLERRM :' || SQLERRM);
          DBMS_OUTPUT.
           put_line (
             'call stack...' || CHR (10) || DBMS_UTILITY.FORMAT_call_STACK ());
          DBMS_OUTPUT.
           put_line (
             'Error_Stack...' || CHR (10) || DBMS_UTILITY.FORMAT_ERROR_STACK ());
          DBMS_OUTPUT.
           put_line (
                'Error_Backtrace...'
             || CHR (10)
             || DBMS_UTILITY.FORMAT_ERROR_BACKTRACE ());
          DBMS_OUTPUT.PUT_LINE ('----------');
          RAISE;
    END;
    SQLCODE :-1722
    SQLERRM :ORA-01722: invalid number
    call stack...
    ----- PL/SQL Call Stack -----
      object      line  object
      handle    number  name
    c0000002a56b4248        11  anonymous block
    Error_Stack...
    ORA-01722: invalid number
    Error_Backtrace...
    ORA-06512: at line 2
    ----------

  • Can't  write right sql query by two tables

    Hello
    Everyone,
    I am trying to get a sql query by two tables,
    table:container
    <pre class="jive-pre">
    from_dest_id     number
    ship_from_desc     varchar
    to_dest_id     number
    </pre>
    table: label_fromat (changeless)
    <pre class="jive-pre">
    SORT_ORDER     number
    PREFIX     varchar2
    VARIABLE_NAME varchar2
    SUFFIX varchar2
    LF_COMMENT varchar2
    </pre>
    the sql which i need is
    a. table CONTAINER 's each column should have LABLE_FORMAT 's PREFIX before and SUFFIX back ,and these columns is connected
    example : the query output should be like this :
    <pre class="jive-pre">
    PREFIX||from_dest_id||SUFFIX ||PREFIX||ship_from_desc||SUFFIX ||PREFIX|| to_dest_id||SUFFIX
    </pre>
    every PREFIX and SUFFIX are come from LABEL_FORMAT's column VARIABLE_NAME (they are different)
    column SORT_ORDER decide the sequence, for the example above: Column from_dest_id order is 1, ship_from_desc is 2,to_dest_id is 3
    b. table LABEL_FORMAT's column VARIABLE_NAME have values ('from_dest_id','ship_from_desc','to_dest_id')
    If table CONTAINER only have one record i can do it myself,
    But actually it is more than one record,I do not know how to do
    May be this should be used PL/SQL,or a Function ,Cursor ,Procedure
    I am not good at these
    Any tips will be very helpful for me
    Thanks
    Saven

    Hi, Saven,
    Presenting data from multiple rows as a single string is called String Aggregation . This page:
    http://www.oracle-base.com/articles/10g/StringAggregationTechniques.php
    shows many ways to do it, suited to different requirements, and different versions of Oracle.
    In Oracle 10 (and up) you can do this:
    SELECT     REPLACE ( SYS_CONNECT_BY_PATH ( f.prefix || ' '
                                   || CASE  f.variable_name
                                        WHEN 'FROM_DEST_ID'
                                       THEN  from_dest_id
                                       WHEN 'SHIP_FROM_DESC'
                                       THEN  ship_from_desc
                                       WHEN 'TO_DEST_ID'
                                       THEN  to_dest_id
                                      END
                                   || ' '
                                   || f.suffix
                               , '~?'
              , '~?'
              )     AS output_txt
    FROM          container     c
    CROSS JOIN     label_format     f
    WHERE          CONNECT_BY_ISLEAF     = 1
    START WITH     f.sort_order     = 1
    CONNECT BY     f.sort_order     = PRIOR f.sort_order + 1
         AND     c.from_dest_id     = PRIOR c.from_dest_id
    saven wrote:If table CONTAINER only have one record i can do it myself,
    But actually it is more than one record,I do not know how to do In that case, why did you post an example that only has one row in container?
    The query above assumes
    something in container (I used from_dest_id in the example above) is unique,
    you don't mind having a space after prefix and before from_dest_id,
    you want one row of output for every row in container, and
    you can identify some string ('~?' in the example above) that never occurs in the concatenated data.

  • How can i write the following statements in Java ???

    Hi Everyone,
    I'm studying UML and according to my textbook, it says if 2 classes have the following relationship then it can be said that there's an association relationship between those 2 classesl.
    Class A and B are associated if :
    - an object of class A sends a message to an object of class B
    - an object of class A creates an object of class B
    - an object of class A has an attribute whose value are objects of class B or collections of objects of class B
    - an object of class A receives a message with an object of class B as an argument.
    However, I dunno how to write those stuff into Java codes. Can someone please kindly write Java codes for those sentences ?? Thanks everyone in advance.

    Sorry guys. I know I shouldn't have asked in the first place without giving it a try first. Yeah, I been doing
    Java without understanding the concept of real OOP and its terms.
    - an object of class A sends a message to an object of class B // ?????
    - an object of class A creates an object of class B // A obj=new A();
    - an object of class A has an attribute whose value are objects of class B or collections of objects of class B // A varB;
    - an object of class A receives a message with an object of class B as an argument. // ?????
    I get confused with the very first line and the last line . I dunno what it means by sending a message but according to what JoachimSauer mentioned
    it's "calling a method" but does that mean even I called an object of the same class within , can i still refers it as sending a message ?? Like what if
    i call a static method of the calling object because I dun think i create an object when I call a static method ?
    Let's say
    class ExampleOne
         public ExampleOne()
              ExampleOne egOne=new ExampleOne();
              egOne.display(); //can i refer to this as egOne object sending a message to an object of itself so the receiver is also egOne ??
         public void displayOne()
              System.out.println("Just an exampleOne");
    class ExampleTwo
         public ExampleTwo()
              ExampleTwo.display(); // here no object creation occurs , just ExampleTwo class sends a message to itself so there's no association i assume .
         public static void displayTwo()
              System.out.println("Just an exampleTwo");
    public class Main
         public static void main(String args[])
              ExampleOne exampleOne=new ExampleOne();
              ExampleTwo exampleTwo=new ExampleTwo();
    }I'm confused. at first , i thought sending a message means passing values as parameters when we call a function and receiving a message means the function
    being called receive values as parameters. Phew, please help me out of this.

  • How can I write this SQL?

    the statement have the question:
         stxh-tdname  length 70
         itab-vbeln       length 10
    select tdobject into table it_stxh
        from stxh
        for all entries in  itab
        where ( tdid = 'Z006' and tdspras = 'E'      and tdname+0(10) = itab-vbeln and tdobject = 'VBBK' ).
    tdname+0(10) = itab-vbeln  ???

    When you define the first Internal Table ITAB, define vbeln as the same type of stxh-tdname.
    Eg.
      data: begin of itab occurs 0,
              vbeln like STXH-TDNAME,
              erdat like vbak-erdat,
              end of itab.
    START-OF-SELECTION.
    Select VBELN
              ERDAT
      from vbak
      into CORRSPONDING FIELDS of table itab.
    Then you can directly use  this ITAB in the next query
      select tdobject into table it_stxh
      from stxh
      for all entries in itab
      where ( tdid = 'Z006' and tdspras = 'E' and tdname = itab-vbeln
      and tdobject = 'VBBK' ).
    Pls reward it if it is useful.

Maybe you are looking for