Concat java variable to a MySql select statement and exeucte

Hi,
I am trying to append a variable to a MySql select statement.
Overview: I need to retrieve data from a MySql database with a java variable as a reference and select the data in the database based on that variable.
CODE THAT I CURRENTLY HAVE:
// Declare variables
Connection conn = null;
Statement st = null;
Resultset rs2 = null;
String st2 = null;
String keyid = null;
// Connect to database
try {
      Class.forName("org.gjt.mm.mysql.Driver").newInstance();
      conn = DriverManager.getConnection("jdbc:mysql://" + mysql_host + ":3306/" + mysql_database, mysql_login, mysql_password);
      st = conn.createStatement();
      // Select data in Database with hanging equal sign
      st2 = ("SELECT * FROM table WHERE keyid= ");
      // Append keyid to hanging equal sign of select statement
      rs2 = st.executeQuery(st2 + keyid);
}This is not working when I try to display the data.

What is not working about it? Is there an error message? Stack Trace?
Where do you get the value of keyId from?
I would suggest that you use a prepared statement rather than building up a sql string like this. It prevents sql injection attacks
// Declare variables
Connection conn = null;
PreparedStatement stmt = null;
Resultset rs2 = null;
String sql= null;
String keyid = null;
// Connect to database
try {
      Class.forName("org.gjt.mm.mysql.Driver").newInstance();
      conn = DriverManager.getConnection("jdbc:mysql://" + mysql_host + ":3306/" + mysql_database, mysql_login, mysql_password);
      // Select data in Database with place holder for parameter
      sql = "SELECT * FROM table WHERE keyid= ?";
       // prepare the statement
      stmt = conn.prepareStatement(sql);
      // set the value of key id to use with the query
      stmt.setString(1, keyId);
      // run the query
      rs2 = st.executeQuery();
catch (Exception e){
  System.out.println("An error occurred " + e.getMessage());
  e.printStackTrace();
finally{
  if (rs2 != null) try { rs2.close(); } catch(SQLException ex){}
  if (stmt != null) try { stmt.close(); } catch(SQLException ex){}
  if (conn != null) try { con.close(); } catch(SQLException ex){}
}

Similar Messages

  • Conditional Mysql select statement

    HI Folks
    can anyone point me in the right direction with a MySQL statement.
    I will try to layout my thinking here:
    I have a form with three inputs area, name and search. I am trying to write a Mysql select statement that selects records from a single table if they match the criteria. Easy for two variables but I'm lost after that.
    1. The form includes these three inputs:
    area - drop down menu (Any as default)
    name - drop down menu (Any as default)
    search box - text area (Blank as default)
    2. The form submits to itself leaving me with these three variables
    $search=$_GET['search']
    $area=$_GET['area']
    $name=$_GET['area']
    SELECT * FROM database WHERE database.description LIKE '%$search%' AND database.area LIKE '$area' AND database.name LIKE '$name'
    3. This is where I get confused. How do I get the SQL to Select everything correctly. I have tried using PHP if/else code to fix it but I end up running around in circles with six different Select statements and haven't yet got that to work.
    So I have come to the conclusion that there must be an easier way.  I see search forms with dozens of  search criteria on websites every day an d I only have 3 - so it can't be this complicated. Right?
    I know I need to start from the beginning again but can anyone let me know how to approach it before I begin?
    Cheers
    Dave

    Typically, I would build the where clause dynamically, based upon the values in your form. If the form field contains 'Any', leave it out of the where clause. So you can test each field value and either append or not to the end of the where clause.

  • Bind Variable in SELECT statement and get the value  in PL/SQL block

    Hi All,
    I would like  pass bind variable in SELECT statement and get the value of the column in Dynamic SQL
    Please seee below
    I want to get the below value
    Expected result:
    select  distinct empno ,pr.dept   from emp pr, dept ps where   ps.dept like '%IT'  and pr.empno =100
    100, HR
    select  distinct ename ,pr.dept   from emp pr, dept ps where   ps.dept like '%IT'  and pr.empno =100
    TEST, HR
    select  distinct loc ,pr.dept   from emp pr, dept ps where   ps.dept like '%IT'  and pr.empno =100
    NYC, HR
    Using the below block I am getting column names only not the value of the column. I need to pass that value(TEST,NYC..) into l_col_val variable
    Please suggest
    ----- TABLE LIST
    CREATE TABLE EMP(
    EMPNO NUMBER,
    ENAME VARCHAR2(255),
    DEPT VARCHAR2(255),
    LOC    VARCHAR2(255)
    INSERT INTO EMP (EMPNO,ENAME,DEPT,LOC) VALUES (100,'TEST','HR','NYC');
    INSERT INTO EMP (EMPNO,ENAME,DEPT,LOC) VALUES (200,'TEST1','IT','NYC');
    INSERT INTO EMP (EMPNO,ENAME,DEPT,LOC) VALUES (300,'TEST2','MR','NYC');
    INSERT INTO EMP (EMPNO,ENAME,DEPT,LOC) VALUES (400,'TEST3','HR','DTR');
    INSERT INTO EMP (EMPNO,ENAME,DEPT,LOC) VALUES (500,'TEST4','HR','DAL');
    INSERT INTO EMP (EMPNO,ENAME,DEPT,LOC) VALUES (600,'TEST5','IT','ATL');
    INSERT INTO EMP (EMPNO,ENAME,DEPT,LOC) VALUES (700,'TEST6','IT','BOS');
    INSERT INTO EMP (EMPNO,ENAME,DEPT,LOC) VALUES (800,'TEST7','HR','NYC');
    COMMIT;
    CREATE TABLE COLUMNAMES(
    COLUMNAME VARCHAR2(255)
    INSERT INTO COLUMNAMES(COLUMNAME) VALUES ('EMPNO');
    INSERT INTO COLUMNAMES(COLUMNAME) VALUES ('ENAME');
    INSERT INTO COLUMNAMES(COLUMNAME) VALUES ('DEPT');
    INSERT INTO COLUMNAMES(COLUMNAME) VALUES ('LOC');
    COMMIT;
    CREATE TABLE DEPT(
    DEPT VARCHAR2(255),
    DNAME VARCHAR2(255)
    INSERT INTO DEPT(DEPT,DNAME) VALUES ('IT','INFORMATION TECH');
    INSERT INTO DEPT(DEPT,DNAME) VALUES ('HR','HUMAN RESOURCE');
    INSERT INTO DEPT(DEPT,DNAME) VALUES ('MR','MARKETING');
    INSERT INTO DEPT(DEPT,DNAME) VALUES ('IT','INFORMATION TECH');
    COMMIT;
    PL/SQL BLOCK
    DECLARE
      TYPE EMPCurTyp  IS REF CURSOR;
      v_EMP_cursor    EMPCurTyp;
      l_col_val           EMP.ENAME%type;
      l_ENAME_val       EMP.ENAME%type;
    l_col_ddl varchar2(4000);
    l_col_name varchar2(60);
    l_tab_name varchar2(60);
    l_empno number ;
    b_l_col_name VARCHAR2(255);
    b_l_empno NUMBER;
    begin
    for rec00 in (
    select EMPNO aa from  EMP
    loop
    l_empno := rec00.aa;
    for rec in (select COLUMNAME as column_name  from  columnames
    loop
    l_col_name := rec.column_name;
    begin
      l_col_val :=null;
       l_col_ddl := 'select  distinct :b_l_col_name ,pr.dept ' ||'  from emp pr, dept ps where   ps.dept like ''%IT'' '||' and pr.empno =:b_l_empno';
       dbms_output.put_line('DDL ...'||l_col_ddl);
       OPEN v_EMP_cursor FOR l_col_ddl USING l_col_name, l_empno;
    LOOP
        l_col_val :=null;
        FETCH v_EMP_cursor INTO l_col_val,l_ename_val;
        EXIT WHEN v_EMP_cursor%NOTFOUND;
          dbms_output.put_line('l_col_name='||l_col_name ||'  empno ='||l_empno);
       END LOOP;
    CLOSE v_EMP_cursor;
    END;
    END LOOP;
    END LOOP;
    END;

    user1758353 wrote:
    Thanks Billy, Would you be able to suggest any other faster method to load the data into table. Thanks,
    As Mark responded - it all depends on the actual data to load, structure and source/origin. On my busiest database, I am loading on average 30,000 rows every second from data in external files.
    However, the data structures are just that - structured. Logical.
    Having a data structure with 100's of fields (columns in a SQL table), raise all kinds of questions about how sane that structure is, and what impact it will have on a physical data model implementation.
    There is a gross misunderstanding by many when it comes to performance and scalability. The prime factor that determines performance is not how well you code, what tools/language you use, the h/w your c ode runs on, or anything like that. The prime factor that determines perform is the design of the data model - as it determines the complexity/ease to use the data model, and the amount of I/O (the slowest of all db operations) needed to effectively use the data model.

  • MySQL Select Statement Help Required

    I am trying to generate a report in VS 2008 (C#) using a mysql select statement but cannot get it right.
    I have groups that meet on a weekly basis on different days. I want to generate a report that shows me all the members that have not attended their group where they have missed 3 meetings in a row.
    Below is the select statement I have tried but it does not give me the results I am looking for. I have tried to look at all the meetings in a 4 week period but would prefer to look at the last 3 meetings that are recorded. Some groups might not record a meeting every week. So I want to look at the last 3 recorded meetings and count each members attendance and only report on the members with more than 3 meetings missed.
    SELECT COUNT(`groupattendance`.`Attended`) AS Attendance, `smallgroupform`.`MeetingDate`, `userinfo`.`FirstName`, `userinfo`.`Surname`, `smallgroup`.`GroupName`, `groupattendance`.`Attended`, `groupattendance`.`UserID`, `groupattendance`.`GroupID`
    FROM ((`anatomy`.`groupattendance` `groupattendance`
    INNER JOIN `anatomy`.`smallgroupform` `smallgroupform` ON `groupattendance`.`FormID` = `smallgroupform`.`FormID`)
    INNER JOIN `anatomy`.`userinfo` `userinfo` ON `groupattendance`.`UserID` = `userinfo`.`UserID`)
    INNER JOIN `anatomy`.`smallgroup` `smallgroup` ON `groupattendance`.`GroupID` = `smallgroup`.`GroupID`
    WHERE (`smallgroupform`.`MeetingDate` >= DATE_SUB(CURDATE(),INTERVAL 4 WEEK) AND `smallgroupform`.`MeetingDate` <= CURDATE()) AND `groupattendance`.`Attended` = 'False'
    GROUP BY `userinfo`.`UserID`
    HAVING Attendance >= 3
    Thanks,
    Garth.

    Hi Garth,
    Seems no one can help you directly. Try googling your SQL request. Someone may be able to help you. At this point its not really a Cr problem.
    One option is to get all the data and add filtering using the record selection formula.
    Thank you
    Don

  • MySql select statement

    Hi All,
    I have java application which suppose to connect to MySql server and print the selected data.
    The application has 4 combo boxes (first item is empty): Name, Customer, Supplier, Status.
    User could choose any of these options. So there are huge number of select combinations.
    Is it possible to create one select statement template something like this:
    PreparedStatement stmt = con.prepareStatement( "SELECT * from database WHERE user_id = ?,
    and customer_id = ?,
    and supplier_id = ?,
    and status = ? " );
    if ( ! ComboBox.getSelectedItem().toString().isEmpty() )
    stmt00.setString( 1, ComboBox.getSelectedItem().toString() );
    else
    stmt00.setString( 1, "*" );
    etc…
    I'm stuck at this part stmt00.setString( 1, "*" ). Is there any way to write statement SELECT * from table WHERE column = * ?
    What is the proper way to write such selection ?
    Thanks in advance,
    Vladimir

    Is there any way to write statement SELECT * from table WHERE column = * ?No, that's invalid SQL.
    What is the proper way to write such selection ?If you need in one case to select a single user, but in another case to select all of them, then you need to handle two different SQL statements.
    1. SELECT * from table WHERE column = value
    2. SELECT * from table
    This has nothing to do with Java.

  • MySql select statement in jsp page

    Ok,
    I need help with this select statement.
    <%
    // Determine what option is set to.
    if(option == null || "".equals(option) || "Verify1".equals(option)){
      if("Verify1".equals(option)){
      // Retrive query specific to submitted form.
      try {
          Class.forName("org.gjt.mm.mysql.Driver").newInstance();
          conn = DriverManager.getConnection("jdbc:mysql://" + mysql_host + ":3306/" + mysql_database, mysql_login, mysql_password);
          st = conn.createStatement();
          rs= st.executeQuery("SELECT organization FROM tblevent_approval WHERE MAX (keyid))";
          // Get query results.
          while(rs.next()){
            organization = rs.getString("organization");
      finally {
            if(rs != null){
              rs.close();
            if(st != null){
              st.close()
            if(conn != null){
              conn.close();
    %>THE ERROR I AM GETTING
    Syntax error, insert ")" to complete Expression

    This line has the closing bracket inside the closing quote for the statement...
    >       rs= st.executeQuery("SELECT organization FROM tblevent_approval WHERE MAX (keyid))";It should be:
    rs= st.executeQuery("SELECT organization FROM tblevent_approval WHERE MAX (keyid)");A simple typo ;-)
    Hope this helps...

  • How to increment variable value in single select statement

    Hi guys
    in this select statement i have hard coded date value but i need to put variable instead of hard coded date and then i want to increment that variable value till sysdate.. i have tried using curser , type tables but they are very very slow .. any experiance guys can give me good hint what should i use.
    my query
    select
    start_dt,
    end_dt,
    hi_start_dt,
    hi_end_dt,
    ph_start_dt,
    ph_end_dt,
    h_start_date,
    h_end_date,
    g_code,
    emp_det.ref,
    u_code,
    costing,
    emp_nm,
    emp_no
    from
    emp_det,
    emp_ph_det,
    emp_hi_det,
    emp_h_det
    where
    emp_det.ref(+) = emp_ph_det.ref
    and emp_hi_det.p_ref(+) = emp_ph_det.p_ref
    and emp_h_det.ph_ref = emp_ph_det.ph_ref
    and emp_h_det.ph_st_dt(+) = emp_hi_det.st_date;
    and to_date('01-MAR-2008') between i.start_dt and nvl(i.end_dt, to_date('01-MAR-2008') +1)
    and to_date('01-MAR-2008') between i.hi_start_dt and nvl(i.hi_end_dt, to_date('01-MAR-2008') + 1)
    and to_date('01-MAR-2008') between i.ph_start_dt and nvl(i.ph_end_dt, to_date('01-MAR-2008') + 1)
    and to_date('01-MAR-2008') between i.h_start_date and nvl(i.h_end_date, to_date('01-MAR-2008') + 1)
    or
    (----emp has left this month
    i.start_dt < i.emp_end_dt
    and i.end_dt between add_months(to_date('01-MAR-2008'), -1) + 1 and to_date('01-MAR-2008')
    and i.hi_start_dt < i.hi_end_dt
    and i.hi between add_months(to_date('01-MAR-2008'), -1) + 1 and to_date('01-MAR-2008')
    and i.ph_start_dt < i.ph_end_dt
    and i.ph_end_dt between add_months(to_date('01-MAR-2008'), -1) + 1 and to_date('01-MAR-2008')
    and i.h_start_date < i.h_end_date
    and i.h_end_date between add_months(to_date('01-MAR-2008'), -1) + 1 and to_date('01-MAR-2008')

    Hi Anurag
    Thanks for the reply.please find my sample data below . below i am only showing data for one employee only.. i want to write a query where i will query for a month like march 2008 and then i need to find out the record for employe where this month march 2008 is between all the start and end dates like it should be between start_dt and end_dt and h_start_date and h_end_date and hi_strt_dt and hi_end_dt and ph_start_dt and ph_end_dt and where all the combination are true show me that record only .. i don't want any other record.
    h_start h_end_
    start_dt      end_dt     date        date          histrt_dt hi_end_dt ph_start_dt ph_end_dt
    1-Sep-07     31-Dec-08     8-Feb-08     31-Aug-08     1-Sep-07     31-Dec-07     8-Feb-08     31-Dec-08
    1-Sep-07     31-Dec-08     1-Sep-07     31-Dec-07     1-Sep-07     31-Dec-07     1-Sep-07     31-Dec-07
    1-Sep-07     31-Dec-08     1-Sep-08     31-Dec-08     1-Sep-07     31-Dec-07     8-Feb-08     31-Dec-08
    1-Sep-07     31-Dec-08     8-Feb-08     31-Aug-08     1-Aug-08     31-Aug-08     8-Feb-08     31-Dec-08
    1-Sep-07     31-Dec-08     1-Sep-07     31-Dec-07     1-Aug-08     31-Aug-08     1-Sep-07     31-Dec-07
    1-Sep-07     31-Dec-08     1-Sep-08     31-Dec-08     1-Aug-08     31-Aug-08     8-Feb-08     31-Dec-08
    1-Sep-07     31-Dec-08     8-Feb-08     31-Aug-08     1-Oct-08     31-Dec-08     8-Feb-08     31-Dec-08
    1-Sep-07     31-Dec-08     1-Sep-07     31-Dec-07     1-Oct-08     31-Dec-08     1-Sep-07     31-Dec-07
    1-Sep-07     31-Dec-08     1-Sep-08     31-Dec-08     1-Oct-08     31-Dec-08     8-Feb-08     31-Dec-08
    1-Sep-07     31-Dec-08     8-Feb-08     31-Aug-08     1-Sep-08     30-Sep-08     8-Feb-08     31-Dec-08
    1-Sep-07     31-Dec-08     1-Sep-07     31-Dec-07     1-Sep-08     30-Sep-08     1-Sep-07     31-Dec-07
    1-Sep-07     31-Dec-08     1-Sep-08     31-Dec-08     1-Sep-08     30-Sep-08     8-Feb-08     31-Dec-08
    1-Sep-07     31-Dec-08     8-Feb-08     31-Aug-08     8-Feb-08     31-Jul-08     8-Feb-08     31-Dec-08
    1-Sep-07     31-Dec-08     1-Sep-07     31-Dec-07     8-Feb-08     31-Jul-08     1-Sep-07     31-Dec-07
    1-Sep-07     31-Dec-08     1-Sep-08     31-Dec-08     8-Feb-08     31-Jul-08     8-Feb-08     31-Dec-08

  • How to use variables in an sql select statement.

    Hi, I have seen examples using the update, but nothing using a select statement.
    I have four variables I am getting from drop down menus in my JSP I set the user selected items to strings.
    How would I create the select statement like this:
    .String XName = request.getParameter("UserInputX");
    rsInResult = stmtInResult.executeQuery("SELECT ColumxX FROM TableZ WHERE ColumnX = XName")Obviously it tries to read "XName" as a column and of course can't find it, how would I set it up to have it see the Value of XName and not the literal XName.

    read this:
    rsInResult = stmtInResult.executeQuery("SELECT ColumxX FROM TableZ WHERE ColumnX = '"+XName+"')
    {code}
    better way is PreparedStatement:
    {code}
         // example code to change password to an user in the USERS table
         String newPWD = "my password";
         String user = "luxjava";
         PreparedStatement prepStat;
         String updatePWD = "UPDATE LOGISTIC.USERS "+
                                  "SET logistic.users.password = ? "+
                                  "WHERE logistic.users.username = ?";
         prepStat = ql.conDb.prepareStatement(updatePWD);
         prepStat.setString(1, newPwd);
         prepStat.setString(2, user);
         int zeroNotFound = prepStat.executeUpdate();
         if (zeroNotFound==0)
              ql.conDb.rollback();
              prepStat.close();
         else
              ql.conDb.commit();
              prepStat.close();
    {code}
    ... use the SQLException to capture errors                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • How user variable table names in select statement

    Dear all,
    I have three table gp1,gp2,g3. i want user variable table in sql query
    for example at oracle forms have a list table showing table names gp1,gp2,gp3
    at form i want user this query
    select gpno from :table where gpno=120;
    how i can specify table name Dynamicly in select query
    Thanks

    Forms_DDL is a one-way street: You can only pass DDL commands TO the database; you cannot get data back using Forms_DDL.
    Exec_SQL is the Forms package that enables dynamic sql within a form. But to retrieve data, you have to make a Exec_SQL call for every column in every row. So it is not a good thing to use, either.
    The ref cursor method should work. You could also retrieve the data into a record group using populate_group_with_query -- it also enables dynamic data retrieval.
    But if you already know you have three distinct tables and you know their names, I would keep it simple and just write three sql select statements.

  • Mysql select statement where = works and LIKE fails

    I am using Flash Builder 4. On the server side I use php and mysql. I created a php dataservice using FB4. My plan had been to allow users to enter a search term and query the database using a "LIKE" statement. FB4 created the php code that I simply modified changing the parameter name. The input parameter is a string.
    public function getT_caseByID($searchTerm) {
    $stmt = mysqli_prepare($this->connection, "SELECT * FROM $this->tablename WHERE (title = ?)");
    $this->throwExceptionOnError();
    mysqli_stmt_bind_param($stmt, 'i', $searchTerm);
    $this->throwExceptionOnError();
    mysqli_stmt_execute($stmt);
    $this->throwExceptionOnError();
    mysqli_stmt_bind_result($stmt, $row->idt_case, $row->title, $row->id_author, $row->comments);
    if(mysqli_stmt_fetch($stmt)) {
          return $row;
    } else {
          return null;
    A look at FB4 shows this code returns data.
    This code works fine but if I make the below change it fails, even when I use the wildcard %. the only change is "=" to "LIKE".
    public function getT_caseByID($searchTerm) {
    $stmt = mysqli_prepare($this->connection, "SELECT * FROM $this->tablename WHERE (title LIKE ?)");
    $this->throwExceptionOnError();
    mysqli_stmt_bind_param($stmt, 'i', $searchTerm);
    $this->throwExceptionOnError();
    mysqli_stmt_execute($stmt);
    $this->throwExceptionOnError();
    mysqli_stmt_bind_result($stmt, $row->idt_case, $row->title, $row->id_author, $row->comments);
    if(mysqli_stmt_fetch($stmt)) {
         return $row;
    } else {
         return null;
    A look into FB4 shows "void".
    Any help would be appreciated. I am using localhost on Apache Server on a development computer with Windows XP.

    correctio0n on the select statement
    select statement code*********
    select
        apspnr astspr aobjnr apspid
        bpsphi bposid
        caufnr cpspel
        dinact dstat
        eudate eusnam eutime "estat
       F~TXT04
        g~estat
        G~TXT04
        into corresponding fields of table itobj
        from proj as a
        inner join prps as b on apspnr = bpsphi
        inner join aufk as c on bpspnr = cpspel
        inner join jest as d on cobjnr = dobjnr
        inner join jcds as e on dobjnr = eobjnr
                             and dstat = estat
        inner join tj02t as f on estat = fistat
        inner join tj30t as g on astspr = gstsma
        for all entries in itparm
        where  apspid = itparm-pspid "or estat = itparm-psy )
        or  bposid = itparm-posid "or estat = itparm-wsy )
        or  caufnr = itparm-aufnr "or estat = itparm-nsy  )
        and ( dinact  'X' or einact  'X')
        and fspras = 'E' and gspras = 'E'.

  • Inline select statement and SQL optimizatino

    Hi everyone,
    I am trying to optimze a script but can't get the fulle explainplan in PL/SQL.
    The problem is that the select statements in de column defenition is not explained. below are the 2 scripts I want to compare:
    SQL1:
    Select
    z.title
    , (select name from members where id =z.id) as name
    , z.id
    from job z
    SQL2
    Select
    z.title
    , d.name
    , z.id
    from job z
    left outer join members d on z.id=d.id
    My question is: what is the effect on performance and cost of the 'inline select' statement of name in SQL1
    hope to hear form you soon
    Harm
    Edited by: HALI on 25-nov-2010 1:14

    In respons to your question below is the output:
    I altered the used names, tablenames etc. according to our privacy pollacy.
    A far as I can see the inline statement is not traced.
    The query with ansi-join:
    xplain plan for
    select
      id as Interne
    , mv.ie_id as Act
    , 'H_W' as Rl
    from testing i
    left outer join resutino m on i.hand=m.id
       left outer join vert mv on m.voor || case when m.voeg is not null then ' '|| m.voeg end ||' '||m.naam = mv.source and mv.field = 'employee'
    explain plan succeeded.
    select * from table(dbms_xplan.display)
    PLAN_TABLE_OUTPUT                                                                                                                                                                                       
    | Id  | Operation            |  Name               | Rows  | Bytes | Cost  |                                                                                                                            
    |   0 | SELECT STATEMENT     |                     |   684 | 47880 |    19 |                                                                                                                            
    |   1 |  HASH JOIN OUTER     |                     |   684 | 47880 |    19 |                                                                                                                            
    |   2 |   HASH JOIN OUTER    |                     |   684 | 22572 |    15 |                                                                                                                            
    |   3 |    TABLE ACCESS FULL | testing             |   684 |  5472 |     7 |                                                                                                                            
    |   4 |    TABLE ACCESS FULL | resutino            |   308 |  7700 |     7 |                                                                                                                            
    |   5 |   TABLE ACCESS FULL  | VERT                |   166 |  6142 |     3 |                                                                                                                            
    Note: cpu costing is off, 'PLAN_TABLE' is old version                                                                                                                                                   
    13 rows selected
    The inline select query:
    xplain plan for
    SELECT
    case when (select ie_id  from vert xov where xov.field = 'field' and source in
              (select m.voor || case when m.voeg is not null then ' '|| m.voegend ||' '||m.naam from resultino m where i.hand= m.id)) is not null then
              'X'||(select ie_id  from vert xov where xov.field = 'field' and source in
              (select m.voor || case when m.voeg is not null then ' '|| m.voegend ||' '||m.naam from resultino m where i.hand= m.id))
         else 'X' || (select ie_id from vert xov where xov.source = 'none' and xov.veld = 'employee')
    end                                                    as  Act,
    'ADM' as  Rol,
    i.id as  Interne
    FROM testing i
    explain plan succeeded.
    select * from table(dbms_xplan.display)
    PLAN_TABLE_OUTPUT                                                                                                                                                                                       
    | Id  | Operation            |  Name         | Rows  | Bytes | Cost  |                                                                                                                                  
    |   0 | SELECT STATEMENT     |               |   684 |  5472 |     7 |                                                                                                                                  
    |   1 |  TABLE ACCESS FULL   | testing       |   684 |  5472 |     7 |                                                                                                                                  
    Note: cpu costing is off, 'PLAN_TABLE' is old version                                                                                                                                                   
    9 rows selected

  • Long running select statement and v$session_longops

    Oracle Version: 10.2.0.4
    I've a long running sql query that takes the estimated 6 minutes to complete and return the result.
    While it's running I'd like to observe it into the view v$session_longops.
    I altered the session that runs the query with
      ALTER SESSION SET timed_statistics=TRUE;The tables it queries have gathered statistics on them.
    However I don't see any rows in the view v$session_longops for the respective SID and serial#. Why is that? What am I missing?
    Thank you!

    Hi,
    Now I understand what you all meant by "loops" here .. Yes, the query does nested loops as one can see from the execution plan. So it could be the reason
    SELECT STATEMENT, GOAL = ALL_ROWS                                  
    SORT GROUP BY                                                             
      CONCATENATION                              
       TABLE ACCESS BY LOCAL INDEX ROWID     TABLE_1
        NESTED LOOPS                                                   
         NESTED LOOPS
          TABLE ACCESS BY GLOBAL INDEX ROWID     TABLE_2      
           INDEX RANGE SCAN                           IPK_t2_CDATE                               
          TABLE ACCESS BY INDEX ROWID     TABLE_3
           INDEX RANGE SCAN                     IPK_T3                            
         PARTITION RANGE ALL                                                 
          INDEX RANGE SCAN     IRGP_REGCODE                        
       TABLE ACCESS BY LOCAL INDEX ROWID     TABLE_1
        NESTED LOOPS                                                  
         NESTED LOOPS          
          TABLE ACCESS BY GLOBAL INDEX ROWID     TABLE_2     
           INDEX RANGE SCAN                       IPK_t2_STATUS          
          TABLE ACCESS BY INDEX ROWID     TABLE_3     
           INDEX RANGE SCAN                       IPK_T3
         PARTITION RANGE SINGLE               
          INDEX RANGE SCAN                     IRGP_REGCODE          

  • In Oracle SQL, cannot use column in select statement and order by

    Hi,
    Is there a work around for this.
    Thanks in advance
    Pablo.

    Hi,
    943981 wrote:
    Hi All,
    This is the error I get:
    ORA-00960: ambiguous column naming in select list
    00960. 00000 - "ambiguous column naming in select list"
    *Cause:    A column name in the order-by list matches more than one select
    list columns.
    *Action:   Remove duplicate column naming in select list.
    Error at Line: 6 Column: 17That error message looks pretty clear to me. What don't you understand?
    Either
    (a) use aliases, so each column has a unique name, or
    (b) remove duplicate columns from the SELECT clause.
    Post your query. It's hard to say exactly what you're doing wrong when we don't know exactly what you're doing.
    For best results, post a complete test script (including CREATE TABLE and INSERT statements, if necessary) that people can to re-create the problem and test their ideas.
    See the forum FAQ {message:id=9360002}

  • Problems with PreparedStatement and MySQL selecting bytes

    Hi,
    i have a problem trying to select information when the "select" has a byte restrict.
    The table in database is:
    CREATE TABLE `positions` (
    `PKID` int(10) unsigned NOT NULL auto_increment,
    `POSCODE` varbinary(30) NOT NULL,
    `ISWTURN` binary(1) NOT NULL,
    `QTT_GAMES` int(10) unsigned NOT NULL default '1',
    PRIMARY KEY (`PKID`),
    UNIQUE KEY `UNIQ_POS` (`POSCODE`,`ISWTURN`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    And the test code to get the qtt_games is :
    conn = DriverManager.getConnection (url,user,pwd);
    byte bcode[] = poscode.getByteArrayCode();
    // bcode is inserted ok in another preparedstatement...
    String query = "SELECT qtt_games FROM positions "+
         "WHERE poscode=? and iswturn=?";
    PreparedStatement pstmt = conn.prepareStatement(query);
    pstmt.setBytes (1,bcode);
    pstmt.setByte (2,poscode.getIsWhiteTurn()); //it returns a byte
    ResultSet rs = pstmt.executeQuery (query);
    When pstmt.executeQuery is reached, it's thrown the exception:
    com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '=? and iswturn=?' at line 1
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2870)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1573)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1665)
    at com.mysql.jdbc.Connection.execSQL(Connection.java:3170)
    at com.mysql.jdbc.Connection.execSQL(Connection.java:3099)
    at com.mysql.jdbc.Statement.execute(Statement.java:695)
    at app.server.bbdd.MYSQLBDManager.getGamesBasicInfo(MYSQLBDManager.java:942)
    at app.server.bbdd.MYSQLBDManager.main(MYSQLBDManager.java:1068)
    Can anybody tell me what's wrong?? I think the query is ok, but don't know what's happening with this...
    Lots of thanks.

    Don't cross-post, it's considered rude:
    http://forum.java.sun.com/thread.jspa?threadID=5122604&messageID=9430056#9430056
    http://forum.java.sun.com/thread.jspa?threadID=5122603&messageID=9430050#9430050
    One to a customer, please.
    %

  • Assign a value to an ODI or Java variable in a KM

    Hi Gurus,
    I'm developing a new KM and I need to get the name of a dblink by calling an Oracle function. How to store the result of a function in an ODI or Java variable in a KM step ?
    And if it is in an Java variable, how to use it in this kind of step (line 7) :
    create or replace view <%=odiRef.getObjectNameDefaultPSchema("L", "" , "W")%><%=odiRef.getInfo("COLL_NAME")%>
         <%=odiRef.getColList("", "[CX_COL_NAME]", ",\n\t", "", "")%>
    as select     <%=odiRef.getPop("DISTINCT_ROWS")%>
         <%=odiRef.getColList("", "[EXPRESSION]", ",\n\t", "", "")%>
    from     <%=odiRef.getSrcTablesList("", "[SCHEMA].[RES_NAME]@"+++*#PROJECT.VARIABLE*+++" [POP_TAB_ALIAS]", ", ", "")%>
    where     (1=1)
    <%=odiRef.getFilter()%>
    <%=odiRef.getJrnFilter()%>
    <%=odiRef.getJoin()%>
    <%=odiRef.getGrpBy()%>
    <%=odiRef.getHaving()%>
    Thanks a lot for your help.
    Best regards

    If it is java variable then your code should looks like this
    create or replace view <%=odiRef.getObjectNameDefaultPSchema("L", "" , "W")%><%=odiRef.getInfo("COLL_NAME")%>
    <%=odiRef.getColList("", "[CX_COL_NAME]", ",\n\t", "", "")%>
    as select     <%=odiRef.getPop("DISTINCT_ROWS")%>
    <%=odiRef.getColList("", "[EXPRESSION]", ",\n\t", "", "")%>
    from     <%=odiRef.getSrcTablesList("", "[SCHEMA].[RES_NAME]@ *<@=java_variable_name@>* [POP_TAB_ALIAS]", ", ", "")%>
    where     (1=1)
    <%=odiRef.getFilter()%>
    <%=odiRef.getJrnFilter()%>
    <%=odiRef.getJoin()%>
    <%=odiRef.getGrpBy()%>
    <%=odiRef.getHaving()%>
    If it is odi variable then your code should looks like this
    create or replace view <%=odiRef.getObjectNameDefaultPSchema("L", "" , "W")%><%=odiRef.getInfo("COLL_NAME")%>
    <%=odiRef.getColList("", "[CX_COL_NAME]", ",\n\t", "", "")%>
    as select     <%=odiRef.getPop("DISTINCT_ROWS")%>
    <%=odiRef.getColList("", "[EXPRESSION]", ",\n\t", "", "")%>
    from     <%=odiRef.getSrcTablesList("", "[SCHEMA].[RES_NAME]@ *#odi_variable_name* [POP_TAB_ALIAS]", ", ", "")%>
    where     (1=1)
    <%=odiRef.getFilter()%>
    <%=odiRef.getJrnFilter()%>
    <%=odiRef.getJoin()%>
    <%=odiRef.getGrpBy()%>
    <%=odiRef.getHaving()%>

Maybe you are looking for

  • Is there a way of syncing your Music Library on iPhone 4 to different computers?

    I have synced my iphone library to a computer and I want to sync it to another computer of mine how can I do that??

  • Estimate AC/DC of a sine signal

    Hi, i capture an analog signal (a sine) with labview and i want to extract several informations from the signal like : Amplitude, offset, peak value, frequency, etc. I almost get what i want, but i can't get the correct value of AC / DC components of

  • Provision account key missing for condition type FRA1 in schema ZIMPOR

    Hi, While maintaining the condition value in PO, the below message displayed. "Provision account key missing for condition type FRA1 in schema ZIMPOR" Thanks and regards Murugesan

  • How to enter values for an Info-object Manually.

    Hi I have to enter certan values manually in the customised info-object which are not available in the BW at the moment. If I go via SE11 I am only getting change option. If I go via SM30 it says The maintenance dialog for ****** is incomplete or not

  • Form Mail vs. Database...

    Hi, I'm debating whether to set up a form to send via formmail (comes in as a regular e.mail) or to go through my host company so that the responses go through a database first. Which is more reliable, or would you think would be best for a form in w