Help with Group By on SQL statement

Iu2019m trying to group by Item Code in the following query, however, I keep receiving the following error message.  Do you know why?
Msg 306, Level 16, State 2, Line 1
The text, ntext, and image data types cannot be compared or sorted, except when using IS NULL or LIKE operator.
SELECT            dbo.OQUT.DocNum,
                  dbo.OQUT.U_UDF_3 AS QuoteNumber,
                  dbo.OQUT.U_QuoteDesc,
                  dbo.OQUT.U_RevQuote,
                  dbo.OQUT.U_RevDate,
                  dbo.OQUT.DocDate,
                  dbo.OQUT.DocDueDate,
                  dbo.OQUT.U_ReqDate,
                  dbo.OQUT.U_DueDate,
                  dbo.OQUT.CardCode,
                  dbo.OQUT.CardName,
                  dbo.OQUT.CntctCode,
                  dbo.QUT1.LineNum,
                  dbo.QUT1.BaseLine,
                  dbo.QUT1.ItemCode,
                  dbo.QUT1.Dscription,
                  SUM(dbo.QUT1.Quantity),
                  SUM(dbo.QUT1.OpenQty),
                  SUM(dbo.QUT1.U_Original_Qty),
                  dbo.QUT1.U_LeadTime,
                  dbo.QUT1.Price,
                  SUM(dbo.QUT1.LineTotal),
                  dbo.QUT1.unitMsr AS SalUnitMsr,
                  dbo.QUT1.U_UDF_12 AS PNQuoted,
                  dbo.QUT1.U_UDF_13 AS MFRQuoted,
                  dbo.QUT1.U_UDF_16 AS MinQty,
                  dbo.QUT1.U_UDF_17 AS MultiQty,
                  dbo.TBC_AMLPriority1.U_Mfg_Name,
                  dbo.TBC_AMLPriority1.U_Mfg_PN,
                  dbo.QUT1.U_Parent,
                  dbo.ITT1.Quantity AS BOMQty,
                  dbo.OCPR.Name
FROM         dbo.OQUT INNER JOIN
                  dbo.QUT1 ON dbo.OQUT.DocEntry = dbo.QUT1.DocEntry LEFT OUTER JOIN
                    dbo.OCPR ON dbo.OQUT.CntctCode = dbo.OCPR.CntctCode LEFT OUTER JOIN
dbo.ITT1 ON dbo.QUT1.ItemCode = dbo.ITT1.Code AND dbo.QUT1.U_Parent =
dbo.ITT1.Father LEFT OUTER JOIN
                  dbo.TBC_AMLPriority1 ON dbo.QUT1.ItemCode = dbo.TBC_AMLPriority1.U_ItemCode
WHERE     (dbo.QUT1.Quantity > 0)and dbo.OQUT.DocNum='1'
GROUP BY    dbo.QUT1.ItemCode,
            dbo.OQUT.DocNum,
            dbo.OQUT.U_UDF_3

Dear,
As per your message you mentioned that u r getting following error "
The text, ntext, and image data types cannot be compared or sorted, except when using IS NULL or LIKE operator."
The error is due to group by of a field whose type is text,ntext.....
if it is text or ntext just replace that field
Convert(varchar(100),fieldName)...
Hope it will help you....
Regards
Sanjay

Similar Messages

  • Help With SUBSTR in dynamic SQL statement

    Following is the dynamic SQL statement.
    EXECUTE IMMEDIATE 'UPDATE table_name pml
    SET pml.'|| con_fields.field ||' = SUBSTR(pml.'||con_fields.field||' ||'' ''||
    (SELECT pml1.'||con_fields.field||'
    FROM table_name pml1
    WHERE pml1.grp_id = '||los_concats.grp_id ||'
    AND pml1.row_id = '||los_concats.row_id||'
    AND pml1.loser_flg = ''Y''),1, '||con_fields.max_length||')
    WHERE pml.grp_id = '||los_concats.grp_id ||'
    AND pml.loser_flg IS NULL ';
    what it does is that it updates a particular field. This field is concatenated by a field of a similar record.
    My problem is with SUBSTR function. Since I am concatenating fields I do not want the field to be updated greater than max_length on that field, the reason why I use SUBSTR. the select query inside SUBSTR works alright with one of the AND condition in a WHERE clause not present. When I add that additional condition it gives me this error.
    ORA-00907: missing right parenthesis.
    Is there any way to get around this problem. Does SQL has other than SUBSTR function which can limit the character length.
    Appreciate it.

    The other alternative I thought about was to do this first
    EXECUTE IMMEDIATE 'SELECT pml.'||con_fields.field||'
    FROM table_name pml
    WHERE pml.grp_id = '||los_concats.grp_id||'
    AND pml.row_id = '||los_concats.row_id||'
    AND pml.loser_flg = ''Y''
    ' INTO v_concat_field;
    write into the variable v_concat_field and then use it into the previous script.
    But on this I get SQL Command not properly terminated, I don't get it Why?
    Donald I tried with your suggested script. It works fine with one of the conditions eliminated. I don't understand what the error trying to say?
    Thanks

  • Help with a really simple SQL statement

    Hi All
    I'm relatively new to SQL and can't get my head round what I believe to be a really simple problem.
    I have a table I want to query called locations. We use locations to mean groups and regions as well as people s ofr example:
    TABLE: LOCATION
    IDENTIFIER----------NAME-----------------PART_OF
    101--------------------USER A---------------123
    123--------------------GROUP A-------------124
    etc
    What I'm trying to write is a statement that will return the 'PART_OF' as the 'NAME' rather than the ID number if the ID = 101.
    I was wondering if a nested select statement would do (select as select etc) but just can't get my head round it!
    Any ideas?
    TIA. Jake.

    Hi Jake,
    It's not clear what you are looking for. If USER A is just Part of GROUP A, a self-join will do:
    SQL> with loc as (select 101 locid, 'USER A' locname, 123 part_of from dual
                 union all
                 select 123 locid, 'GROUP A' locname, 124 part_of from dual
                 union all
                 select 124 locid, 'REGION A' locname, null part_of from dual)
    -- End of test data
    select l1.locid, l1.locname, l2.locname part_of
      from loc l1, loc l2
    where l2.locid(+) = l1.part_of
         LOCID LOCNAME  PART_OF
           101 USER A   GROUP A
           123 GROUP A  REGION A
           124 REGION A        
    3 rows selected.But if you want USER A to be part of REGION A, then you need a hierarchia lquery:
    SQL> with loc as (select 101 locid, 'USER A' locname, 123 part_of from dual
                 union all
                 select 123 locid, 'GROUP A' locname, 124 part_of from dual
                 union all
                 select 124 locid, 'REGION A' locname, null part_of from dual)
    -- End of test data
    select l1.locid, l1.locname, connect_by_root(locname) part_of
      from loc l1
    start with part_of is null
    connect by prior locid = part_of
         LOCID LOCNAME  PART_OF
           124 REGION A REGION A
           123 GROUP A  REGION A
           101 USER A   REGION A
    3 rows selected.Regards
    Peter

  • Help with a very slow sql statement

    Hi this statement takes 10 seconds to run and is run a lot, can anyone help me speed it up.
    Each section in itself is quick but when i add the IN section it slows down, probably because there is 20291 rows in the view v_allitems.
    anyone know how i can speed up?
    select ITEMTYPE,
    ITEMID,
    NOTESID,
    NOTES,
    DUEDATE,
    OPENDATE,
    SUBJECT,
    TYPE,
    STATUS,
    OWNER,
    CREATEBY,
    CREATEDATE,
    ITEMCODE
    FROM v_allitems
    where
    ITEMCODE in ( 'ACT,'||4264) OR ITEMCODE IN
    (SELECT pcchildcode
    ||','
    || pcchild item
    FROM afpc
    CONNECT BY pcparent = prior pcchild
    AND pcparentcode = prior pcchildcode START
    WITH pcparent = 232
    AND pcparentcode = 'CAS'
    UNION ALL
    SELECT pcparentcode
    ||','
    || pcparent item
    FROM afpc
    CONNECT BY pcchild = prior pcparent
    AND pcchildcode = prior pcparentcode START
    WITH pcchild =4264
    AND pcchildcode = 'ACT'
    )

    Something to just try i guess (wild guessing here).
    WITH
       itemcodes AS
       SELECT
          DISTINCT ItemCode
       FROM
          SELECT 'ACT,' || 4264 AS ItemCode
          FROM DUAL
             UNION ALL    
             SELECT pcchildcode || ',' || pcchild item AS ItemCode
             FROM afpc
             CONNECT BY  pcparent       = prior pcchild
             AND         pcparentcode   = prior pcchildcode
             START WITH  pcparent       = 232
             AND         pcparentcode   = 'CAS'
                UNION ALL
             SELECT pcparentcode || ',' || pcparent item AS ItemCode
             FROM afpc
             CONNECT BY  pcchild     = prior pcparent
             AND         pcchildcode = prior pcparentcode
             START WITH  pcchild     = 4264
             AND         pcchildcode = 'ACT'
    SELECT
       v.ITEMTYPE,
       v.ITEMID,
       v.NOTESID,
       v.NOTES,
       v.DUEDATE,
       v.OPENDATE,
       v.SUBJECT,
       v.TYPE,
       v.STATUS,
       v.OWNER,
       v.CREATEBY,
       v.CREATEDATE,
       v.ITEMCODE
    FROM v_allitems v,  itemcodes i
    WHERE v.ItemCode  = i.ItemCode;Assuming (probably a good assumption) that's not good, how long does this query take to finish for you?
             SELECT pcchildcode || ',' || pcchild item AS ItemCode
             FROM afpc
             CONNECT BY  pcparent       = prior pcchild
             AND         pcparentcode   = prior pcchildcode
             START WITH  pcparent       = 232
             AND         pcparentcode   = 'CAS'
                UNION ALL
             SELECT pcparentcode || ',' || pcparent item AS ItemCode
             FROM afpc
             CONNECT BY  pcchild     = prior pcparent
             AND         pcchildcode = prior pcparentcode
             START WITH  pcchild     = 4264
             AND         pcchildcode = 'ACT'

  • I need help with this code error "unreachable statement"

    the error_
    F:\Java\Projects\Tools.java:51: unreachable statement <-----------------------------------------------------------------------------------------------------------------THIS
    int index;
    ^
    F:\Java\Projects\Tools.java:71: missing return statement
    }//end delete method
    ^
    F:\Java\Projects\Tools.java:86: missing return statement
    }//end getrecod
    ^
    3 errors
    import java.util.*;
    import javax.swing.*;
    import java.awt.*;
    public class Tools//tool class
    private int numberOfToolItems;
    private ToolItems[] toolArray = new ToolItems[10];
    public Tools()//array of tool
    numberOfToolItems = 0;
    for(int i = 0; i < toolArray.length; i++)//for loop to create the array tools
    toolArray[i] = new ToolItems();
    }//end for loop
    }//end of array of tools
    public int search(int id)//search mehtod
    int index = 0;
    while (index < numberOfToolItems)//while and if loop search
    if(toolArray[index].getID() == id)
    return index;
    else
    index ++;
    }//en while and if loop
    return -1;
    }//end search method
    public int insert(int id, int numberInStock, int quality, double basePrice, String nm)//insert method
    if(numberOfToolItems >= toolArray.length)
    return 0;
    int index;
    index = search(id); <-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------HERE
    if (index == -1)
    toolArray[index].assign(id,numberInStock, quality, basePrice,nm);
    numberInStock ++;
    return 1;
    }//end if index
    }//end if toolitem array
    return -1;
    }//end insert method
    public int delete(/*int id*/)//delete method
    }//end delete method
    public void display()//display method
    for(int i = 0; i < numberOfToolItems; i++)
    //toolArray.display(g,y,x);
    }//end display method
    public String getRecord(int i)//get record method
    // return toolArray[i].getName()+ "ID: "+toolArray[i].getID()
    }//end getrecod
    }//end class
    Edited by: ladsoftware on Oct 9, 2009 6:08 AM
    Edited by: ladsoftware on Oct 9, 2009 6:09 AM
    Edited by: ladsoftware on Oct 9, 2009 6:10 AM
    Edited by: ladsoftware on Oct 9, 2009 6:11 AM

    ladsoftware wrote:
    Subject: Re: I need help with this code error "unreachable statement"
    F:\Java\Projects\Tools.java:51: unreachable statement <-----------------------------------------------------------------------------------------------------------------THIS
    int index;
    ^
    F:\Java\Projects\Tools.java:71: missing return statement
    }//end delete method
    ^
    F:\Java\Projects\Tools.java:86: missing return statement
    }//end getrecod
    ^
    3 errorsThe compiler is telling you exactly what the problems are:
    public int insert(int id, int numberInStock, int quality, double basePrice, String nm)//insert method
    if(numberOfToolItems >= toolArray.length)
    return 0; // <<== HERE you return, so everyting in the if block after this is unreachable
    int index;
    index = search(id);  //< -----------------------------------------------------------------------------------------------------------------HERE
    if (index == -1)
    toolArray[index].assign(id,numberInStock, quality, basePrice,nm);
    numberInStock ++;
    return 1;
    }//end if index
    }//end if toolitem array
    return -1;
    }//end insert method
    public int delete(/*int id*/)//delete method
    // <<== HERE where is the return statement?
    }//end delete method
    public String getRecord(int i)//get record method
    // return toolArray.getName()+ "ID: "+toolArray[i].getID() <<== HERE you commented out the return statement
    }//end getrecod
    }//end class

  • HELP!!! the session hang with a merge into sql statement

    This problem is due to merge into a bug caused it??
    i have a product run on 10.2.0.4 . OS is aix 5.3 .
    today i found the product running over 24,000 sec and the current sql have run 23,734.
    Anomaly the sql Should be a quick end but run so long time.
    the awrsql report sql plan is
    Execution Plan
    Id Operation Name Rows Bytes Cost (%CPU) Time
    0 MERGE STATEMENT 4 (100)
    1 MERGE TP_B_RB013_GL_MID
    2 VIEW
    3 NESTED LOOPS 1 4048 4 (50) 00:00:01
    4 TABLE ACCESS BY INDEX ROWID TP_B_RB013_GL_MID 1 3549 0 (0)
    5 INDEX RANGE SCAN IDX_GL_RB013_MID 1 0 (0)
    6 VIEW PUSHED PREDICATE 1 499 4 (50) 00:00:01
    7 WINDOW SORT PUSHED RANK 1 586 4 (50) 00:00:01
    8 HASH JOIN 1 586 3 (34) 00:00:01
    9 TABLE ACCESS BY INDEX ROWID GL_HIST_RB013 1 124 0 (0)
    10 INDEX SKIP SCAN IDX_GL_RB013 1 0 (0)
    11 TABLE ACCESS FULL GL_EVENT 1 462 2 (0) 00:00:01
    sql_fulltext
    MERGE INTO TP_B_RB013_GL_MID TP
    USING (SELECT TRAN_NO,
    B.EVENT_DEESC,
    ROW_NUMBER () OVER (PARTITION BY TRAN_NO ORDER BY B.EVENT_DESC) I
    FROM GL_HIST_RB013 A, GL_EVENT B
    WHERE EVENT_TYPE IS NOT NULL AND A.EVENT_TYPE = B.EVENT_ID AND B.SDATE = :B1
    ) RES
    ON ( RES.TRAN_NO = TP.BATCH_NO AND RES.I = 1 AND TP.REPORT_DATE = :B1 )
    WHEN MATCHED THEN
    UPDATE SET TP.EVENT_DESC = RES.EVENT_DESC
    Focus is the table "GL_EVENT" have 0 row,the sql should do nothing.
    This problem is due to merge into a bug caused it??
    last is awrsqlrpt Please note cputime and buffer gets
    WORKLOAD REPOSITORY SQL Report
    Snapshot Period Summary
    DB Name DB Id Instance Inst Num Release RAC Host
    FTLPRD 3272430330 FTLPRD 1 10.2.0.4.0 NO bj1finteldb0
    Snap Id Snap Time Sessions Curs/Sess
    Begin Snap: 5022 26-11?-11 21:00:35 127 12.1
    End Snap: 5030 27-11?-11 05:00:40 127 14.0
    Elapsed: 480.09 (mins)
    DB Time: 626.55 (mins)
    SQL Summary DB/Inst: FTLPRD/FTLPRD Snaps: 5022-5030
    Elapsed
    SQL Id Time (ms)
    a4j4qaqkvxr08 ##########
    MERGE INTO TP_B_RB013_GL_MID TP USING (SELECT TRAN_NO, B.EVENT_DESC, ROW_NUMBER
    () OVER (PARTITION BY TRAN_NO ORDER BY B.EVENT_DESC) I FROM GL_HIST_RB013 A, GL_
    EVENT B WHERE EVENT_TYPE IS NOT NULL AND A.EVENT_TYPE = B.EVENT_ID AND B.SDATE =
    :B1 ) RES ON ( RES.TRAN_NO = TP.BATCH_NO AND RES.I = 1 AND TP.REPORT_DATE = :B1
    SQL ID: a4j4qaqkvxr08 DB/Inst: FTLPRD/FTLPRD Snaps: 5022-5030
    -> 1st Capture and Last Capture Snap IDs
    refer to Snapshot IDs witin the snapshot range
    -> MERGE INTO TP_B_RB013_GL_MID TP USING (SELECT TRAN_NO, B.EVENT_DESC, R...
    Plan Hash Total Elapsed 1st Capture Last Capture
    # Value Time(ms) Executions Snap ID Snap ID
    1 3274057091 23,733,870 0 5024 5030
    Plan 1(PHV: 3274057091)
    Plan Statistics DB/Inst: FTLPRD/FTLPRD Snaps: 5022-5030
    -> % Total DB Time is the Elapsed Time of the SQL statement divided
    into the Total Database Time multiplied by 100
    Stat Name Statement Per Execution % Snap
    Elapsed Time (ms) ########## N/A 63.1
    CPU Time (ms) 23,734 N/A 94.7
    Executions 0 N/A N/A
    Buffer Gets 371,326,923 N/A 84.8
    Disk Reads 16,740 N/A 0.2
    Parse Calls 1 N/A 0.0
    Rows 0 N/A N/A
    User I/O Wait Time (ms) 145,938 N/A N/A
    Cluster Wait Time (ms) 0 N/A N/A
    Application Wait Time (ms) 0 N/A N/A
    Concurrency Wait Time (ms) 2,348 N/A N/A
    Invalidations 0 N/A N/A
    Version Count 7 N/A N/A
    Sharable Mem(KB) 435 N/A N/A
    Execution Plan
    Id Operation Name Rows Bytes Cost (%CPU) Time
    0 MERGE STATEMENT 4 (100)
    1 MERGE TP_B_RB013_GL_MID
    2 VIEW
    3 NESTED LOOPS 1 4048 4 (50) 00:00:01
    4 TABLE ACCESS BY INDEX ROWID TP_B_RB013_GL_MID 1 3549 0 (0)
    5 INDEX RANGE SCAN IDX_GL_RB013_MID 1 0 (0)
    6 VIEW PUSHED PREDICATE 1 499 4 (50) 00:00:01
    7 WINDOW SORT PUSHED RANK 1 586 4 (50) 00:00:01
    8 HASH JOIN 1 586 3 (34) 00:00:01
    9 TABLE ACCESS BY INDEX ROWID GL_HIST_RB013 1 124 0 (0)
    10 INDEX SKIP SCAN IDX_GL_RB013 1 0 (0)
    11 TABLE ACCESS FULL GL_EVENT 1 462 2 (0) 00:00:01
    Full SQL Text
    SQL ID SQL Text
    a4j4qaqkvxr0 MERGE INTO TP_B_RB013_GL_MID TP USING (SELECT TRAN_NO, B.EVENT_DE
    ESC, ROW_NUMBER () OVER (PARTITION BY TRAN_NO ORDER BY B.EVENT_DE
    SC) I FROM GL_HIST_RB013 A, GL_EVENT B WHERE EVENT_TYPE IS NOT NU
    LL AND A.EVENT_TYPE = B.EVENT_ID AND B.SDATE = :B1 ) RES ON ( RES
    .TRAN_NO = TP.BATCH_NO AND RES.I = 1 AND TP.REPORT_DATE = :B1 ) W
    HEN MATCHED THEN UPDATE SET TP.EVENT_DESC = RES.EVENT_DESC

    Pl do not spam the forums with duplicate posts - HELP !!!  session pending or suspend beacause a merginto sql

  • Help needed writing simple PL/SQL statement

    Hi,
    I need to run the following delete statement in a PL/SQL procedure but for it to commit every 1000 rows or so. Can anyone help?
    DELETE
    FROM IDIS.YPROCRULES A
    WHERE 1 = 1
    AND NOT EXISTS (SELECT 'X' FROM IDIS.YPROCCTRL B WHERE A.SEQ_0 = B.SEQ_0)
    Thanks
    Mark

    The fastest most efficient way of doing the delete is to write it in one sql statement as you have done.
    Commiting every 1000 rows means you have to use row by row processing. A lot of us call this slow by slow processing.
    Every time you commit in a loop , you increase the risk of snapshot too old error, plus you actually slow down the processing, as well as give you issues with regards to what happens if your process fails after x iterations. (some of your data is commited, other data is not, how do you restart the process)
    The correct approach is to have appropriately sized rollback/undo segments.

  • Help with "ORA-06511: PL/SQL: cursor already open"

    I've tried numerous variations on this piece of code and I always get the same result. I'm sure this is painfully obvious to an experienced PL/SQL person.
    Any help will be appreciated!
    Thank You!
    1 DECLARE
    2 CURSOR EMP_CURSOR IS SELECT last_name from employees;
    3 current_last_name varchar2(25);
    4 BEGIN
    5 IF EMP_CURSOR%ISOPEN
    6 THEN
    7 dbms_output.put_line ('cursor is already open');
    8 close EMP_CURSOR;
    9 END IF;
    10 dbms_output.put_line ('opening cursor');
    11 OPEN EMP_CURSOR;
    12 FOR item in EMP_CURSOR LOOP
    13 FETCH EMP_CURSOR INTO current_last_name;
    14 EXIT WHEN EMP_CURSOR%NOTFOUND;
    15 dbms_output.put_line (item.last_name);
    16 END LOOP;
    17 CLOSE EMP_CURSOR;
    18* END;
    19 /
    DECLARE
    ERROR at line 1:
    ORA-06511: PL/SQL: cursor already open
    ORA-06512: at line 2
    ORA-06512: at line 12

    Mathieu,
    Log in as anotherSchema and grant select on 'IDsTable' to the current user.
    SQL> r
      1  create or replace function f1(theID varchar2) return mytype pipelined is
      2  out varchar2(30);
      3  cursor myCursor (x varchar2) is select * from scott.emp where job=x;
      4  begin
      5  for rec in myCursor(theID) loop
      6  pipe row(rec.ename);
      7  end loop;
      8  return;
      9* end;
    Warning: Function created with compilation errors.
    SQL> show errors
    Errors for FUNCTION F1:
    LINE/COL ERROR
    3/33     PL/SQL: SQL Statement ignored
    3/53     PL/SQL: ORA-00942: table or view does not exist
    6/1      PL/SQL: Statement ignored
    6/10     PLS-00364: loop index variable 'REC' use is invalid
    SQL> connect scott
    Enter password: *****
    Connected.
    SQL> grant select on emp to testuser;
    Grant succeeded.
    SQL> connect testuser
    Enter password: ****
    Connected.
    SQL> create or replace function f1(theID varchar2) return mytype pipelined is
      2  out varchar2(30);
      3  cursor myCursor (x varchar2) is select * from scott.emp where job=x;
      4  begin
      5  for rec in myCursor(theID) loop
      6  pipe row(rec.ename);
      7  end loop;
      8  return;
      9  end;
    10  /
    Function created.
    SQL> disconnect
    Disconnected from Oracle9i Enterprise Edition Release 9.2.0.3.0 - 64bit Production
    With the Partitioning option
    JServer Release 9.2.0.3.0 - Production
    SQL>

  • Help with inserting values to sql database

    Hello everyone I am having this problem with how to fill my values in my sql statement, if you look below you will notice i have set up the values to be the length of the arr (arrayList).
    could someone please let me now how i should put there values in.
    thanks for yr time
    piper3
      try {
                                                    String data = "jdbc:odbc:myProject";
                                                        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                                                        Connection con = DriverManager.getConnection(data,"","");
                                                 StringBuffer sb = new StringBuffer();
                                                 Iterator it1 = arr.iterator();
                                                 while (it1.hasNext())
                                                      if (sb.length() > 0)
                                                           sb.append(",");
                                                           sb.append(it1.next());
                                                      //takes the items of the arInterim
                                                      //int iCountInterim = arInterim.size();
                                                      int er = arr.size();
                                                      String sInterim = new String();
                                                      String sql = new String();
                                                      for(int i2 = 0; i2 < er; i2++){
                                                           sInterim = sInterim + sQuestion;
                                                           if(i2 < (er-1)){
                                                                sInterim = sInterim + sComma;
                                                           sql = "INSERT into Ben (" + sb.toString() + ") values (" + sInterim + ")";
                                                           System.out.println(sql);
                                                           PreparedStatement prepStmt = con.prepareStatement(sql);
                                                           /*prepStmt.setString(1, "hello");
                                                           prepStmt.setString(2, "hi");
                                                           prepStmt.setString(3, "bye");
                                                           prepStmt.executeUpdate();
                                                           prepStmt.close();*/
                                                      con.close();               
                                                 } catch (Exception e1) {
                                                             System.err.println("Got an exception! ");
                                                             System.err.println(e1.getMessage());
                                                      //System.out.println();//.size());//tempkey+"\n"+tempvalue);

    you should write a prepared statement like this:
    PreparedStatement updateSales = con.prepareStatement(
    "UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?");
    where "?" is a placeholder for the values you want to use.
    Then later when you want to actually update your database, first set the placeholders to your values (stored in your array for example) using a statement like this:
    updateSales.setString(2, "Colombian");
    //sets the 2. placeholder in the statement to the value "Colombian"
    after having set all placeholders to a specific value, execute your statement:
    updateSales.executeUpdate();
    your code should like:
    sql = "INSERT into Ben values (?,?,?)";
    PreparedStatement prepStmt = con.prepareStatement(sql);
    prepStmt.setString(1, "hello");
    prepStmt.setString(2, "hi");
    prepStmt.setString(3, "bye");
    prepStmt.executeUpdate();
    prepStmt.close();
    HTH
    Christine

  • Help!  Syntax Error in SQL statement

    Hello. I'm getting an error message and I'm just not seeing
    where I went wrong. The SQL statement is:
    updateSQL = "UPDATE TrainingHistory SET Status='" &
    fFormat(Request.Form(cStatus)) & "', StatusComments='" &
    fFormat(Request.Form(cStatusComments)) & " WHERE Training_ID="
    & fFormat(Request.Form(cTrainingID))
    The error message is:
    [Microsoft][ODBC Microsoft Access Driver] Syntax error in
    string in query expression '' WHERE Training_ID=9054'.
    I've been looking at it for a while. Not sure where I went
    wrong. Here is a more complete version of the code:
    <%
    Function fFormat(vText)
    fFormat = Replace(vText, "'", "''")
    End Function
    Sub sRunSQL(vSQL)
    set cExecute = Server.CreateObject("ADODB.Command")
    With cExecute
    .ActiveConnection = MM_coldsuncrea_lms_STRING
    .CommandText = vSQL
    .CommandType = 1
    .CommandTimeout = 0
    .Prepared = true
    .Execute()
    End With
    End Sub
    If Request.Form("action")="update" Then
    'Set variables for update
    Dim updateSQL, i
    Dim cTrainingID, cStatus, cStatusComments
    'Loop through records on screen and update
    For i = 1 To fFormat(Request.Form("counter"))
    'Create the proper field names to reference on the form
    cTrainingID = "Training_ID" & CStr(i)
    cStatus = "Status" & CStr(i)
    cStatusComments = "StatusComments" & CStr(i)
    'Create the update sql statement
    updateSQL = "UPDATE TrainingHistory SET Status='" &
    fFormat(Request.Form(cStatus)) & "', StatusComments='" &
    fFormat(Request.Form(cStatusComments)) & " WHERE Training_ID="
    & fFormat(Request.Form(cTrainingID))
    'Run the sql statement
    Call sRunSQL(updateSQL)
    Next
    'Refresh page
    Response.Redirect("ClassUpdateRoster.asp?Training_ID=") &
    (rsClassDetails.Fields.Item("event_ID").Value)
    End If
    %>

    You need another single quote after the double quote before
    the WHERE clause. You are not closing the single quote you used to
    delimit the value for StatusComments.

  • Same WITH used in many SQL statements

    Hi,
    I have a need to use the same WITH clause in many places of my code. Is it ever possible to code without writing the same code in every SQL which need my WITH?
    Thanks in advance.

    As Tubs mentioned, views.
    There only 2 basic methods of modularisation of SQL source code. Using the WITH clause (modularises in the same statement), or VIEWS (modularises across SQL statements).
    Using PL/SQL functions or pipelined tables are poor choices for SQL code modularisation. And should not be considered. These tools address a different set of requirements.

  • Group By in sql statement....

    I have the following sql statement:
    SELECT ROWNUM AA, EPONYMO||' '||ONOMA FNAME ,CODE_ERGAZOMENOY_TYPE_ID,MV_SIGK_KATAST_MINA.SUM_ODOIP_EXODA,
    MV_SIGK_KATAST_MINA.SUM_HMERISIA_APOZIMIOSI, MV_SIGK_KATAST_MINA.SUM_SINOLO,
    MV_SIGK_KATAST_MINA.SUM_KRATISI_MTPY,
    MV_SIGK_KATAST_MINA.SUM_KRATISI_G_EPIM, MV_SIGK_KATAST_MINA.SUM_KRATISI_TADKY,
    MV_SIGK_KATAST_MINA.ETOS , (SELECT NVL(SUM(DAYS),0) FROM MOD3_PRAGMATOP_ODOIP WHERE
    CODE_ERGAZOMENOY_TYPE_ID=MV_SIGK_KATAST_MINA.CODE_ERGAZOMENOY_TYPE_ID AND
    MINAS||'/'||ETOS BETWEEN :P_MONTH_APO||'/'||:P_ETOS_APO AND :P_MONTH_EOS||'/'||:P_ETOS_EOS) PRAGM_ODOIP ,
    (SELECT DAYS FROM REF_DIKAIOUM_MERES_EKTOS_EDRAS
    WHERE SYSDATE BETWEEN DATES_APO AND DATES_EOS AND
    SEQ_CODE_ERGAZOMENOY_TYPE_ID=MV_SIGK_KATAST_MINA.CODE_ERGAZOMENOY_TYPE_ID) DIKAIOUM_ODOIP , MV_SIGK_KATAST_MINA.SUM_SINOLO-(MV_SIGK_KATAST_MINA.SUM_KRATISI_MTPY+MV_SIGK_KATAST_MINA.SUM_KRATISI_G_EPIM+MV_SIGK_KATAST_MINA.SUM_KRATISI_TADKY) NET_POSO
    FROM MV_SIGK_KATAST_MINA  , REF_ERGAZOMENOS
    WHERE REF_ERGAZOMENOS.SEQ_CODE_ERGAZOMENOY=MV_SIGK_KATAST_MINA.CODE_ERGAZOMENOY_TYPE_ID
      AND MV_SIGK_KATAST_MINA.MINAS||'/'||MV_SIGK_KATAST_MINA.ETOS BETWEEN :P_MONTH_APO||'/'||:P_ETOS_APO AND :P_MONTH_EOS||'/'||:P_ETOS_EOS
    and i want to compute the sum of the above selected columns adding a group by clause.....Is it possible.....?????
    Some sample data...
    MINAS     ETOS     CODE_ERGAZOMENOY_TYPE_ID     SUM_ODOIP_EXODA     SUM_HMERISIA_APOZIMIOSI     SUM_SINOLO     SUM_KRATISI_MTPY     SUM_KRATISI_G_EPIM     SUM_KRATISI_TADKY
    07     2007     161     505,95     508,64     972,74     10,32     25,48     20,28
    07     2007     230     85,3     78,25     163,55     1,59     3,92     3,12
    06     2007     230     0     9,78     9,78     0     0     0
    06     2007     161     421,75     254,31     676,06     5,17     12,74     10,14
    07     2007     26     118,35     303,21     330,81     6,17     15,19     12,09
    05     2007     230     0     9,78     9,78     0     0     0
    07     2007     236     328,25     88,04     407,04     1,78     4,41     3,51I use OracleDB10g...
    Sorry for the format of the sample data.....!!!!
    Thanks, a lot
    Simon
    Message was edited by:
    sgalaxy

    To columns... which do have the 'SUM_' prefix ....such as ...
    EPONYMO||' '||ONOMA ,
    CODE_ERGAZOMENOY_TYPE_ID,
    MV_SIGK_KATAST_MINA.ETOS,
    PRAGM_ODOIP (nested select query),
    DIKAIOUM_ODOIP (nested select query)
    I THINK... I HAVE DONE IT... I'LL CHECK IT MORE CAREFULLY...
    Thanks...a lot
    Simon
    Message was edited by:
    sgalaxy

  • Please Help with group chat probs

    I don't get any sound or vibe notification for my group chats also In my group chats if a pic is posted and then comments made on that pic I can't scroll up or down to see all comments. This is something I need to fix as we use pic with chats at work.  I can't get the info I need.  If any one could help with this problem please do. This problem has only been since I upgraded to the newest bbm messenger last week. I have the Q10. I pulled the battery and sims card but this did nothing to fix the problem. Please if anyone can help!
    Thank you all  

    Please make sure you are using TRUCN() in your GROUP BY expression. This function will truncate the date by removing time content.
    Best of luck!

  • Just a helpful SAP note for slow SQL statements

    Hi Guys,
    Just wanted to share this SAP note with you. I am sure many of you might have gone through it.
    [SAP Note 155413 - Analysis of slow SQL statements|https://websmp130.sap-ag.de/sap(bD1lbiZjPTAwMQ==)/bc/bsp/spn/sapnotes/index2.htm?numm=155413]
    Cheers,
    Abu

    >
    ZAFCO ABAP wrote:
    > Hi Guys,
    >
    > Just wanted to share this SAP note with you. I am sure many of you might have gone through it.
    >
    > [SAP Note 155413 - Analysis of slow SQL statements|https://websmp130.sap-ag.de/sap(bD1lbiZjPTAwMQ==)/bc/bsp/spn/sapnotes/index2.htm?numm=155413]
    >
    > Cheers,
    > Abu
    Hi,
    I would bet not as many as you might think -  many questions here suffering form not GOING through
    the analysis before they post it here. 
    Meantime I think questions to SQL statement performance here will only be answered when the execution plan on the statement  is posted with it.
    bye
    yk

  • Pleasse help me with this error in SQL statement

    Please tell me the error in this query:
    the Error given is
    java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Syntax error in INSERT INTO statement
    given :
    Databse is MS Access
    In the databse :
    account - text
    number - text
    date - date/time
    vendor - text
    Connection connection = t.getConnection();
    /* t - some object containing a connection*/
    Statement stmt = connection.createStatement();
    stmt.executeUpdate("INSERT INTO Bills (account, number, date, vendor)
    VALUES ('vai', '23', 10/12/2006, 'jaadya')");

    I would imagine the problem is with the date. Different DBs have different date formats. To avoid that problem, use a PreparedStatement.
    java.sql.Date date = ...;
    PreparedStatement ps = con.prepareStatement("INSERT INTO Bills (account, number, date, vendor) VALUES (?, ?, ?, ?)");
    ps.setString(1, "vai");
    ps.setString(2, "23);
    ps.setDate(3, date);
    ps.setString(4, "jaadya");
    ps.executeUpdate();This saves you from having to deal with vendors' various date formats, keeps you from having to escape special characters in strings, and prevents SQL injection.

Maybe you are looking for