Using Like Clause in Prepared Statement

Hi,
I want to use LIKE clause in prepared statement. This is not returning any record.
This is the query. Please help me in this.
SELECT EMPLYR_GRP,EMPLYR_GRP_NAME FROM EMPLOYER_GROUP WHERE EMPLYR_GRP_NAME LIKE ? AND EMPLYR_GRP = ?
This is giving Oracle SQL Error.
SELECT EMPLYR_GRP,EMPLYR_GRP_NAME FROM EMPLOYER_GROUP WHERE EMPLYR_GRP_NAME LIKE %?% AND EMPLYR_GRP = ?

The first variant should work just fine as long as you use stmt.setString(1, '%' + pattern + '%') to set the parameter. The second query is just plain wrong.
Alin.

Similar Messages

  • Using "IN" clause in prepared statement

    I need to set string for an IN clause in a sql query. But I am not able to get the format in which the string to be set.
    TABLENAME.COLUMNAME IN ( ? )
    preparedStatement.setString( 'A' , 'B' );
    It doesn't works
    help me out?

    I need to set string for an IN clause in a sql query.
    But I am not able to get the format in which the
    string to be set.
    TABLENAME.COLUMNAME IN ( ? )
    preparedStatement.setString( 'A' , 'B' );
    It doesn't works
    help me out?You can't do that; the "?" in the SQL for a prepared statement is not used for arbitrary string replacement. Each "?" has to correspond to a data value that will be bound later.
    In other words, you can do:
    "SELECT * FROM tablename WHERE keyvalue in (?, ?, ?)";
    pstmt.setString(1,"A");
    pstmt.setString(2,"A");
    pstmt.setString(3,"A");There is no way to have a single "?" replaced by a variable-length list.

  • Create Index to use Like Clause

    Hi All,
    I want one of my query to use a index which runs with a LIKE Clause. I have not done that before but i have heard and seen through forums that its possible to create indexes for a column with Like Clause using function based index.
    Function
    Request the forum users to achieve my objective. Let me list down what i have done.
    Function
    CREATE OR REPLACE FUNCTION RND_LIKE(P_NO IN VARCHAR2)
    RETURN VARCHAR2 IS
    RESULT VARCHAR2(240);
    BEGIN
    RETURN P_NO||'%';
    END RND_LIKE;
    SELECT ENAME FROM EMP WHERE ENAME LIKE RND_LIKE('A')
    Here based on this function i want to create a function based index and force the same to my query. Request the forum users to help me out in this.
    Thanks
    Edited by: ramarun on Dec 18, 2009 9:26 PM

    In the case you had there , Oracle would use an index on ename in a query if you were to type A% in the ename item on a Form. You wouldn't need a function index for that.
    Here's the link to the documentation to create a function based index http://download-uk.oracle.com/docs/cd/B28359_01/server.111/b28310/indexes003.htm#i1006674

  • How to use "where" clause in modify statement

    Hi
    can any1 telll me is it possible to use a where clause in a modify statemetn. I want to use modify statemetn  to insert a new recoed in a database table.
    Regards
    Sabahuddin Ahmed

    MODIFY itab - itab_lines
    Syntax :
    ... itab FROM wa TRANSPORTING comp1 comp2 ... WHERE log_exp.
    With these additions the MODIFY statement assigns the content of the comp1 comp2 ... components of the wa work area specified after TRANSPORTING to all lines in the itab table that meet the logical condition log_exp. The wa work area must be compatible with the line type of the internal table.
    The TRANSPORTING addition has the same effect as changing individual lines. The WHERE addition can only be specified together with the TRANSPORTING addition. After WHERE, any logical expression can be specified in which the first operand of each individual comparison is a component of the internal table. All logical expressions are therefore possible, with the exception of IS ASSIGNED, , and IS SUPPLIED. It is not possible to dynamically specify a component using bracketed character-type data objects.
    While for standard tables and hashed tables all lines in the internal table are checked for the logical expression of the WHERE statement, for sorted tables, optimized access can be achieved by checking at least one opening part of the table key for parity using AND linked queries in the logical expression.
    Example
    Change the contents of the planetype component for all lines in the sflight_tab internal table in which this component contains the value p_plane1 to the value p_plane2.
    PARAMETERS: p_carrid TYPE sflight-carrid,
                p_connid TYPE sflight-connid,
                p_plane1 TYPE sflight-planetype,
                p_plane2 TYPE sflight-planetype.
    DATA sflight_tab TYPE SORTED TABLE OF sflight
                     WITH UNIQUE KEY carrid connid fldate.
    DATA sflight_wa TYPE sflight.
    SELECT *
           FROM sflight
           INTO TABLE sflight_tab
           WHERE carrid = p_carrid AND
                 connid = p_connid.
    sflight_wa-planetype = p_plane2.
    MODIFY sflight_tab FROM sflight_wa
           TRANSPORTING planetype WHERE planetype = p_plane1.
    reward if useful

  • How to use where clause with get statement in LDB programs

    Hi All,
    I am using logical databse in my report program.I am not getting how to use the where clause in the get statement is it possible to use?or if not possible only option is we should filter it after get statment is right?Can you please some body throw some idea on this?
    Regards
    Mahesh

    Hi,
    Reffer these links
    http://help.sap.com/saphelp_nw04/helpdata/en/9f/db9bfa35c111d1829f0000e829fbfe/content.htm
    http://help.sap.com/saphelp_nw04/helpdata/en/9f/db9b5e35c111d1829f0000e829fbfe/frameset.htm
    http://help.sap.com/saphelp_nw04/helpdata/en/c6/8a15381b80436ce10000009b38f8cf/frameset.htm
    /people/srivijaya.gutala/blog/2007/03/05/why-not-logical-databases
    reward if helpful
    Thanks,
    Suma.

  • Problem in using LIKE addition in SELECT statement

    HI Experts,
    Have a small query for you :
    While selecting from Database I want to fetch all records which have the field name like "HR_".
    I wrote following select query :
    l_tsobj TYPE tst01-dname VALUE 'HR_%',
    SELECT * INTO TABLE ltst01 FROM tst01 WHERE dname LIKE l_tsobj.
    During debugging it shows me all records like HR_ & all records like HRL.
    Not sure why it is fetching records like HRL from database .
    In table tst01 total number of records having HR_ = 1231
    but the above query select in total 1231 + 2000( records having HRL ..... pattern also ).
    I want to restrict data selection at database level only & not at internal table level . Please suggest.
    Thanks,
    Abhinav.

    Hi,
    you have to use ESCAPE statement.
    DATA:     
      l_tsobj TYPE tst01-dname VALUE 'HR/_%'.
    SELECT *
      INTO TABLE ltst01
      FROM tst01
      WHERE dname LIKE l_tsobj ESCAPE '/'.
    Regards Marcel

  • Using like Operator in Prepeared Statement

    PreparedStatement s2=dbcon.prepareStatement("Select phone,dnc_message from gsw_donotcall_list_tab where phone=? or dnc_message like ?");
    s2.setString(1,number);
    s2.setString(2,"%"+smessage+"%");
    ResultSet result=s2.executeQuery();
    rowfound=result.next();
    (Using SQL Server, I am Accepting Parameters from the User by a HTML Page, the user may enter full or partial message, but need to display all the records Satisfying the Criterai
    I tried this but dosnt work for DNC_message Field
    Can anyone help me i am in great need of this

    The problem with that is it produces the following query:
    UPDATE COFFEES SET SALES = 75 WHERE COF_NAME LIKE 'Colombian'Which they also show as a normal Statement (rather than a PreparedStatement) and they claim it will work. Well, in most databases it will work, only if COF_NAME contains exactly "Columbian", just like an "=". If you also want it to return "Columbian Prime" or "Wild Columbian" or whatever, your out of luck without the wildcards, and PreparedStatement does not insert them. If you don't belive it works this way, then test it yourself:
    create table TEST_IT (
      Bogus VARCHAR(20) Primary Key
    insert into TEST_IT values ('AAA');
    insert into TEST_IT values ('ABA');
    insert into TEST_IT values ('ABC');
    SELECT * From Test_It Where Bogus LIKE 'A';
    SELECT * From Test_It Where Bogus LIKE 'AAA';
    SELECT * From Test_It Where Bogus LIKE '%A%';And inspect what the three select statements return.
    Edit: I must apologise, and ask the OP what Driver he is using. This may be somewhat Driver dependent. Using the MySQL 3.1.6 Driver and MySQL 4.1.9, it did not escape the "%" symbols and so
    setString(1, "%A%");returned 3 rows. So the reason yours is not, may be dependent on the Driver and/or vendor. But in any case, the example shown in the tutorial (the Statement version) would still not work (at least in most DBs).

  • Using LIKE in a conditional statement

    I'm trying to color code a column if another column is LIKE "1-%" but there isn't a like option. How is this accomplished?

    there is a workaround for this.
    say you have 2 column
    A---------------------B
    1-A----------------ABC
    1-C----------------bcd
    2-E----------------xyz
    create a dummy column which will have only first two characters of column A for ex
    A---------------------B--------------C
    1-A----------------ABC-----------1-
    1-C----------------bcd------------1-
    2-E----------------xyz-------------2-
    now implement the conditional formatting using this dummy column and hide this in your report. you wil get wat you need.

  • How to write statement using LIKE statement in jsp

    hi
    I am new to jsp. I would like to retrive the data from database using like command. But my query dosen't work well. Can you help me in this topic.
    String name = request.getParameter("username");
    int i = st.executeQuery("select * from emp where empname LIKE '%name%'");
    Plase help me..
    Thanking you
    sure...

    Using LIKE :
    ==========
    The following SQL statement will return persons with first names that start with an 'O':
    SELECT * FROM Persons
    WHERE FirstName LIKE 'O%'
    The following SQL statement will return persons with first names that contain the pattern 'la':
    SELECT * FROM Persons
    WHERE FirstName LIKE '%la%'
    Hope this might have helped you
    REGARDS,
    RaHuL

  • Using prepared statements in java

    Hi
    I have question on proper usage of prepared statements.
    PreparedStatement ps;
    public methoda(){
    ps=conn.prepareStatement(sqlQry);
    ps.setInt(1,2);
    ps.execute();
    In the above case I am creating new references to prepared statement (ps)each time I invoke methoda. So am I still using the advantage of prepared statements that is prepare a statement once and execute it multiple times. Or in the above case, the DB knows that this has been executed before and does not prepare it second time and just executes it.
    thanks

    The database stores execution plans for previous statements that were executed. So even tho you create a new PreparedStatement each time, it will still be an improvement.
    Even if you don't use prepared statements those plans are cached. Problem is that you must reuse the exact same sql to get the benefit.
    So if you do
    select password from users where user="dave";
    a hundred times, the database most likely will only create the plan once.
    Problem is of course, that
    select password from users where user="yelapa";
    is a completely different sql statement sofar as the database knows.
    Thus, the value of Prepared statements.
    select password from users where user=?
    is what the database sees no matter what user is running it.

  • Prepared Statement with ORDER BY

    I am trying to use order by with prepared statement but it is not ordering.
    String sql = "SELECT * FROM MATERIAL WHERE (LOWER(NAMEE) LIKE ('%' || ? || '%') ORDER BY ? ";
    PreparedStatement ps=CM.getStatement(sql);
    ps.setString(1,p);
    ps.setString(2,sort);
              ResultSet r = ps.executeQuery();
    Can any one tell me how do I use prepared statement with order by

    You can not parameterize column names and such, only literals. You should build the ORDER BY clause dynamically.

  • Beginner question about prepared statements...PLEASE help! :-)

    First let me say thanks for the assistance. This is probably really easy to do, but I'm new to JSP and can't seem to figure it out.
    I want to dynamically populate a table that shows whether a particular person has an appointment at a given date and time with a user. To do this, I want to query the MySQL database for the lastname of the person with the appointment that occurs with the user at the year, month, date, and time, in question.
    THE CODE BELOW DOESN'T WORK (obviously) BUT SOMEWHAT ILLUSTRATES WHAT I'M TRYING TO ACCOMPLISH:
    <%
    Driver DriverTestRecordSet = (Driver)Class.forName(MM_website_DRIVER).newInstance();
    Connection ConnTestRecordSet = DriverManager.getConnection(MM_website_STRING,MM_website_USERNAME,MM_website_PASSWORD);
    PreparedStatement StatementTestRecordSet = ConnTestRecordSet.prepareStatement("SELECT lastname FROM appts_pid1 WHERE user_id='<%=(((Recordset1_data = Recordset1.getObject(user_id))==null || Recordset1.wasNull())?"":Recordset1_data)%>' AND year='<%= yy %>' AND month='<%= months[mm] %>' AND date='<%= dates[dd] %>' AND appttime='16:15:00'");
    ResultSet TestRecordSet = StatementTestRecordSet.executeQuery();
    boolean TestRecordSet_isEmpty = !TestRecordSet.next();
    boolean TestRecordSet_hasData = !TestRecordSet_isEmpty;
    Object TestRecordSet_data;
    int TestRecordSet_numRows = 0;
    %>
    The real problem comes in the prepared statement portion. If I build the prepared statement with static values like below, EVERYTHING WORKS GREAT:
    PreparedStatement StatementTestRecordSet = ConnTestRecordSet.prepareStatement("SELECT lastname FROM appts_pid1 WHERE user_id='1' AND year='2002' AND month='October' AND date='31' AND appttime='16:15:00'");
    But when I try to use dynamic values, everything falls apart. It's not that the values aren't defined, I use the user_id, year <%= yy %>, month <%= months[mm] %>, etc. elsewhere on the page with no problems. It's just that I can't figure out how to use these dynamic values within the prepared statement.
    Thanks for reading this far and thanks in advance for the help!!!!

    Hi PhineasGage
    You are little bit wrong in your
    your preparedStatement.
    Expression tag within scriptlet tag is invalid.
    Whenever you are appending the statement with
    expression tag, append it with "+" and remove
    expression tag.
    Hopefully it will work
    ThanksThanks for the response!
    I know that the expression tag within scriptlet tag is invalid. I just need a workaround for what I want to do.
    I'm unclear what you mean by "Whenever you are appending the statement with expression tag, append it with a "+" and remove expression tag".
    Could you give an example?
    In the meantime, I've been trying to digest the docs on prepared statements and have changed the code to look like:
    PreparedStatement StatementTestRecordSet = ConnTestRecordSet.prepareStatement("SELECT lastname FROM appts_pid1 WHERE user_id= ? AND year= ? AND month= ? AND date= ? AND appttime='13:15:00'");
    StatementTestRecordSet.setInt(1,1);
    StatementTestRecordSet.setInt(2,2002);
    StatementTestRecordSet.setString(3,"October");
    StatementTestRecordSet.setInt(4,31);
    Again, WITH THE STATIC VALUES, THIS WORKS FINE...but when I try to use expressions or variables like below, things don't work:
    StatementTestRecordSet.setInt(2,<%= yy %>);
    Obviously, I'm doing something wrong, but there has to be a way to use variables within the prepared statement.
    ALSO, the values are being passed to this page via URL in the form:
    samplepage?user_id=1&year=2002&month=October&date=31
    Based upon this information, is there another way (outside of stored procedures in the db) to do what I want to do? I'm open to ideas.

  • Running explain plan on a prepared statement

    I'm using IBatis to run queries against an Oracle database. IBatis runs the queries as prepared statements. I want to run explain plan on the prepared statements.
    I already have a shim -- a proxy java.sql.Connection object -- that takes the SQL used to create a prepared statement (e.g., "select a, b, c from table d where c = ?"), returns a proxy java.sql.PreparedStatement, and then on the PreparedStatement's execute(), interpolates the bound parameters into the SQL statement, and runs Explain Plan on that (e.g, preparedStatement.setInt(5) is called, followed by preparedStatement.execute(), which results in my proxy running "explain plan for select a, b, c from table d where c = 5;")
    Using Spring configuration, I can transparently insert the shim and get explain plans for all queries run through that Connection.
    The problem is this: I'm explaining the plan for the SQL with the bound parameters, not necessarily the SQL run for the prepared statement.
    Assume that in the above example, there exists an index on column c in table d, and that 5% of d's rows have the value 1, 15% have the value 2, and 80% have the value 3.
    For "select a, b, c from table d where c = 1", Oracle will use the index. But for "select a, b, c from table d where c = 3", Oracle will do a full table scan.
    What I want to know is what Oracle will do for "select a, b, c from table d where c = ?" when "?" is an unknown, arbitrary value subsequently bound to 1 or to 3.
    As I understand it, the query plan for a prepared statement is done once, when the prepared statement is created. At execute time (as I understand it), the query plan is not reformulated based on the actual bound values (though partition pruning is recalculated).
    So how can I find out what query plan is actually be used for prepred statement?
    Thanks.

    I already have a shim -- a proxy java.sql.Connection object -- that takes the SQL used to create a prepared statement I believe explain plan is part of PL/SQL rather than external to it.
    As such you can pass it via a prepared statement. It is just a matter of getting the syntax correct. And of course collecting the result.
    The syntax is going to be be something like the following. You would use it just like you use the existing sql.
    begin
       select ... from ... where c = ?;
    endThe result might be returned a result sets (plural). If so you would need to code appropriately for that.

  • Tunning query with LIKE clause

    Hi, is there any chance to improve execution plan for SQL query which is using LIKE clause?
    Query:
    SELECT * FROM [TABLE_NAME] WHERE ADDRESS LIKE :1 ESCAPE '\';
    | Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
    | 0 | SELECT STATEMENT | | 112K| 18M| 11361 (1)| 00:02:17 |
    |* 1 | TABLE ACCESS FULL| [TABLE_NAME] | 112K| 18M| 11361 (1)| 00:02:17 |
    Execution plan is far from ideal. Table has several millions of records.
    This query is used by application to seach using patterns...
    Any ideas?
    Thx in advance!

    This example isn't entirely realistic. Your table T has only 1 column which is also indexed. Apparently, for small enough tables of one column it will search the entire index for the wildcard value. But if I add a second column, or base the single column version on a larger table, the optimizer uses a full table scan:
    SQL> drop   table t;
    Table dropped.
    SQL> CREATE TABLE t AS SELECT DBMS_RANDOM.STRING('a',100) a
      2                          ,DBMS_RANDOM.STRING('a',100) b
      3                    FROM user_objects;
    Table created.
    SQL>
    SQL> CREATE INDEX t_idx ON t (a) COMPUTE STATISTICS;
    Index created.
    SQL>
    SQL> SET autotrace traceonly explain
    SQL>
    SQL> SELECT *
      2  FROM t
      3  WHERE a LIKE '%acb%';
    Execution Plan
       0      SELECT STATEMENT Optimizer=CHOOSE (Cost=2 Card=1 Bytes=100)
       1    0   TABLE ACCESS (FULL) OF 'T' (Cost=2 Card=1 Bytes=100)
    SQL> drop   table t;
    Table dropped.
    SQL> CREATE TABLE t AS SELECT DBMS_RANDOM.STRING('a',100) a
      2                       --   ,DBMS_RANDOM.STRING('a',100) b
      3                    FROM all_objects;
    Table created.
    SQL>
    SQL> CREATE INDEX t_idx ON t (a) COMPUTE STATISTICS;
    Index created.
    SQL>
    SQL> SET autotrace traceonly explain
    SQL>
    SQL> SELECT *
      2  FROM t
      3  WHERE a LIKE '%acb%';
    Execution Plan
       0      SELECT STATEMENT Optimizer=CHOOSE (Cost=20 Card=399 Bytes=39900)
       1    0   TABLE ACCESS (FULL) OF 'T' (Cost=20 Card=399 Bytes=39900)

  • Batch updates with callable/prepared statement?

    The document http://edocs.bea.com/wls/docs70/oracle/advanced.html#1158797 states
    that "Using Batch updates with the callableStatement or preparedStatement is
    not supported". What does that actually mean? We have used both callable and prepared
    statements with the batch update in our current project (with the Oracle 817 db).
    It seems to run ok anyway.

    So the documentation should state that batch updates do not work ok in old versions
    of JDriver for Oracle, BUT work correctly with newer version. Additionally, batch
    updates work ok when used with Oracle supplied jdbc-drivers?
    "Stephen Felts" <[email protected]> wrote:
    Support for addBatch and executeBatch in the WLS Jdriver for Oracle was
    added in 7.0SP2.
    It was not available in 6.X or 7.0 or 7.0SP1.
    "Janne" <[email protected]> wrote in message news:3edb0cdc$[email protected]..
    The document http://edocs.bea.com/wls/docs70/oracle/advanced.html#1158797
    states
    that "Using Batch updates with the callableStatement or preparedStatementis
    not supported". What does that actually mean? We have used both callableand prepared
    statements with the batch update in our current project (with the Oracle817 db).
    It seems to run ok anyway.

Maybe you are looking for

  • Mavericks won't install on newest mac mini fusion drive

    I have a mac mini, latest version.  I have a fusion drive. Mavericks won't install on that drive.  I get this message: This disk doesn't use the GUID Partition Table scheme. Use Disk Utility to change the partition scheme. Select the Disk, choose the

  • Load a file stored in a Jar Archive

    Dear all, I have a text file stored in a Jar Archive and I want to obtain a File instance of the text file from the jar file. The reason for this is because I have a method which read in a File instance of the file. From my understanding, one can obt

  • Quality Issues on Export

    I'm having a heck of a time with this. I'm shooting with a Sanyo Xacti, whose native format is MP4 burned to an SD card. Since FCE won't handle these files directly, I'm transcoding to DVCPRO50 with MPEG Streamclip. I bring these into FCE and everyth

  • Item category group used for scrap materials

    hello gurus Can u pls tell me what is the item category group used for scrap materials in the material master? Thanks in advance Warm Regards Prashant.

  • How to get selection screen details of any report dynamically

    Hi We have a requirement where we need to submit different reports based upon  certain conditions. I need to know FM or other way around to fetch the details of selection screen (name of selection screen parameters or select option and whether its a