Trouble with city, state in Mysql Query

Hello,
I am having trouble with a query I am trying to setup.  Basically, I want the user to type in their city.  Then I want the system to ask them which city,state combo is theirs.  So if they enter "Washington" the system will return:
Select your city/state:
Washington, NJ
Washington, PA
Washington, DE
City and state are stored as two fields in my mysql DB.  I was considering using 'select distinct' but I wasnt sure how it would work in relation to two fields.  So how would I go about making sure washington, nj only appears once (its in a database where there will be multiple washington, NJ listed).
So anyone have any ideas or code samples they have used to do something like this?
Thanks in advance,
Mark

davella wrote:
City and state are stored as two fields in my mysql DB.  I was considering using 'select distinct' but I wasnt sure how it would work in relation to two fields.  So how would I go about making sure washington, nj only appears once (its in a database where there will be multiple washington, NJ listed).
DISTINCT works the same way for single field or multiple fields.  It returns all distinct combinations of the values in the columns you have listed.
SELECT  DISTINCT City, State
FROM     Table
WHERE  City = 'Washington'
(Data) City, State
Washington, NJ
Washington, PA
Washington, NJ
Washington, DE
Washington, NJ
Washington, PA
So for your two columns it would distinct combinations of the "City" and "State" values.  But why are there multiple "Washington, NJ" records? Are they actually different cities or duplicate records?
(Results)
Washington, NJ
Washington, PA
Washington, DE

Similar Messages

  • Help with City, State Field

    Hi
    I need help in take one field with the City, State to 2 fields. One with City and the other State. I know how to take 2 fields into 1 but what is the script for 1 into 2 using the "," has the divider?
    Thank you in advance!

    Have a look here: http://w3schools.com/jsref/jsref_split.asp

  • Strange results with Insert statement having select query

    Hi all,
    I am facing a strange issue with Insert statement based on a select query having multiple joins.
    DB- Oracle 10g
    Following is the layout of my query -
    Insert into Table X
    Select distinct Col1, Col2, Col3, Col4, Function(Col 5) from Table A, B
    where trunc(updated_date) > = trunc(sysdate-3)
    and join conditions for A, B
    Union
    Select Col1, Col2, Col3, Col4, Function(Col 5) from Table C, D
    trunc(updated_date) > = trunc(sysdate-3)
    and join conditions for C, D
    Union
    .... till 4 unions. all tables are residing in the local Database and not having records more than 50,000.
    If I execute above insert in a DBMS job, it results into suppose 50 records where as if I execute the select query it gives 56 records.
    We observed following things-
    a) no issue with size of tablespace
    b) no error while inserting
    c) since query takes lot of time so we have not used Cursor and PLSQL block for inserting.
    d) this discrepancy in number of records happens frequently but not everytime.
    e) examined the records left out from the insert, there we couldn't find any specific pattern.
    f) there is no constraint on the table X in which we are trying to insert. Also tables A, B, C....
    I went through this thread -SQL insert with select statement having strange results but mainly users are having either DB Links or comparison of literal dates, in my case there is none.
    Can somebody explain why is the discrepancy and what is the solution for it.
    Or atleast some pointers how to proceed with the analysis.
    Edited by: Pramod Verma on Mar 5, 2013 4:59 AM
    Updated query and added more details

    >
    Since I am using Trunc() in the where clause so timing should not matter much. Also I manually ruled out records which were updated after the job run.
    >
    The first rule of troubleshooting is to not let your personal opinion get in the way of finding out what is wrong.
    Actually this code, and the process it represents, is the most likely CAUSE of the problem.
    >
    where trunc(updated_date) > = trunc(sysdate-3)
    >
    You CANNOT reliably use columns like UPDATED_DATE to select records for processing. Your process is flawed.
    The value of that column is NOT the date/time that the data was actually committed; it is the date/time that the row was populated.
    If you insert a row into a table right now, using SYSDATE (8am on 3/5/2013) and don't commit that row until April your process will NEVER see that 3/5/2013 date until April.
    Here is the more typical scenario that I see all the time.
    1. Data is inserted/updated all day long on 3/4/2013.
    2. A column, for example UPDATED_DATE is given a value of SYSDATE (3/4/2013) in a query or by a trigger on the table.
    3. The insert/update query takes place at 11:55 PM - so the SYSDATE values are for THE DAY THE QUERY BEGAN
    4. The data pull begins at 12:05 am (on 3/5/2013 - just after midnight)
    5. The transaction is COMMITTED at 12:10 AM (on 3/5/2013); 5 minutes after the data pull began.
    That data extract in step 4 will NEVER see those records! They DO NOT EXIST when the data pull query is executed since they haven't been committed.
    Even worse, the next nights data pull will not see them either! That is because the next pull will pull data for 3/5/2013 but those records have a date of 3/4/2013. They will never get processed.
    >
    Job timing is 4am and 10pm EST
    >
    Another wrinkle is when data is inserted/updated from different timezones and the UPDATED_DATE value is from the CLIENT pc or server. Then you can get even more data missed since the client dates may be hours different than the server date used for the data pull process.
    DO NOT try to use UPDATED_DATE type columns to do delta extraction or you can have this issue.

  • Problems with prepared statement in MYSQL.

    I 've this code:
    String sql = "UPDATE dcr SET Fecha=?, Origen=?, Destino=?, Mensaje=?, Estado=? WHERE IDDCR=? AND IDUsuario=?";
    PreparedStatement st = cn.prepareStatement(sql);
    SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
    java.sql.Date sqlDate = java.sql.Date.valueOf(fmt.format(this.fecha));
    st.setDate(1, sqlDate);
    st.setString(2, this.origen);
    st.setString(3, this.destino);
    st.setString(4, this.mensaje);
    st.setString(5, this.estado);
    st.setString(6, this.primaryKey);
    st.setString(7, this.usuario);
    I receive a SQLException with this message "Callable statments not supported" when the line "PreparedStatement st = cn.prepareStatement(sql)" is executed.
    My JDBC Driver is "mysql-connector-java-3.0.11-stable-bin" and my server is "*MySQL 4.0.17-max"*.
    Anybody see where is the problem?
    Tnaks in advance.
    Ricardo.

    I've more information about this problem.
    If I take my code and put it in a class with a main function it works fine.
    The original code is a part of a DAO pattern object that is invoked by a servlet (is the storeObject function).
    The servlet create a record, send a native TCP/IP transaction to a external system and whit this code update the record previously created with the result of the transaction.
    The system uses connection pooling. But the conection used in create of the record is diferent from the used in this code. (It's returned to the Datasource) All objects of the database process are closed in a finaly block before return the connection. (Statements, PreparedStatements , ResultSets, etc...)
    Thanks in advance.
    Ricardo

  • Trouble with multi state object

    How do i build a graphic step by step with the previous state still showing?

    You add the previous state to the next one and keep building it that way.
    Bob

  • Trouble with SQL Statements

    Hello all that can help,
    i am programming in Ready to Program to connect to a VideoShop database using SQL statements.
    I am having trouble when using single and double inverted commas. eg vs.updateRentTable ("DELETE FROM RentTable WHERE CustId=);
    but instead of specifiying the CustId i want to make it a variable id so that i can delete any name i want according to their ID.
    also i am wondering if it is possible to write data from a database into a text file? is it possible to use Printwriter?
    Looking forward to your help,
    Manuking16

    Hi Manuking_16,
    Your question should be posted on a sql forum, not on a JDBC forum. Anyway. Just looking for answers, right?
    1) If your datatype is INT, you do not use either quotes " or single quotes in your SQL statement
    DELETE FROM RentTable WHERE CustId= 12345.
    To build the SQL String in JAVA just write:
    {code}String sqlStatement = "DELETE FROM RentTable WHERE CustId = " + custID; // custID will be casted to String.{code}
    2) Use preparedStatement
    {code}PreparedStatement pStm = conn.prepareStatement(�DELETE FROM RentTable WHERE CustId = ?");
    pStm.setInt(1, customerID);
    int numberOfDeletedLines = pStm.execute();3) If you want to enter the real name to do the deletion
    DELETE FROM RentTable WHERE CustId IN (select custID FROM Customer WHERE name = "joe bob johnson")
        To build the SQL String in JAVA just write: String sqlStatement = "DELETE FROM RentTable WHERE CustId IN (select custID FROM Customer WHERE name = '" + sCustomerName + "' )"; // just copy & pasteHope I got your question right.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Trouble with IIF statement in SSRS report builder

    hi....
    I have an expression field that isn't working.  They are Dynamics GP tables, and I am trying to show converted currencies:
    =IIF (Fields!Currency.Value=RTrim("Z-US$"), Fields!ORCPTCOST.Value
    , Fields!ORCPTCOST.Value / CDEC(Fields!ExchangeRate.Value))
    The true part is bolded.  when the report shows, it always comes up as
    #Error. If the currency is  "Z-MXN$", it calculates it fine. 
    So why is my true part not working?
    thanks!
    ~george

    Hi George,
    Based on my research, this issue can be caused by
    IIF is not an expression, it is a function with three parameters:
    IIF(Condition, ValueIfTrue, ValueIfFalse)
    Note that all parameters are evaluated before being passed to the function. We can still get an error, because the erroneous expression is still evaluated even when the condition should mean that it
    isn't. For example, when the currency is "Z-US$", the ExchangeRate field returns
    a stream of letters which cannot be changed to decimal type. Or the ExchangeRate field returns 0, then the denominator is 0, the division makes no sense. So it displays #Error.
    To fix this issue, we can assign a value that doesn’t affect the expression result to ExchangeRate field when it is
    a stream of letters or equal to 0. The expression below is for your references:
    =IIF (Fields!Currency.Value=RTrim("Z-US$"), Fields!ORCPTCOST.Value , Fields!ORCPTCOST.Value / CDEC(iif(IsNumeric(Fields!ExchangeRate.Value)=false or Fields!ExchangeRate.Value=0, 1, Fields!ExchangeRate.Value)))
    If there are any other questions, please feel free to ask.
    Thanks,
    Katherine Xiong
    If you have any feedback on our support, please click
    here.
    Katherine Xiong
    TechNet Community Support

  • A trouble with "LIKE" in a select statement

    Hi!
    I'm having trouble with "LIKE" in a select statement...
    With Access I can make the following and everything works well:
    SELECT name, birthday
    FROM client
    WHERE birthday LIKE '*/02/*';
    but if try to do it in my application (it uses Access), it doesn't work - I just can't understand that!!!
    In my application the "month" is always the currently month taken from the "System". Look what I'm doing...
    String query1 = "SELECT name, birthday " +
              "FROM client " +
              "WHERE birthday " +
              "LIKE '*/" +
              pMonth +
              "/*' " +
              "ORDER BY birthday ASC ";
    ResultSet rs = statement1.executeQuery(consulta1);
    boolean moreRecords = rs.next();
    The variable "moreRecords" is always "false", the query returns nothing although the table "client" has records that attend the query.
    Please, anyone can help me?! It's a little bit urgent.
    Thanks,
    Katia.

    Hi Katia,
    I'll bet the problem lies with the characters you're using to escape the LIKE clause. You're using the ones that Access likes to see, but that's not necessarily what's built into the JDBC-ODBC driver class.
    You can find out what the correct escape wildcard characters are from the java.sql.DatabaseMetaData.getSearchStringEscape() method. It'll tell you what to use in the LIKE clause.
    I'm not 100% sure about your code. It doesn't use query1 anywhere. I'd do this:
    String query = "SELECT name, birthday FROM client WHERE birthday LIKE ? ORDER BY birthday ASC";
    PreparedStatement statement = connection.createStatement(query);
    String escape = connection.getMetaData().getSearchStringEscape();
    String test = escape + '/' + pMonth + '/' + escape;
    statement.setString(1, test);
    ResultSet rs = statement.executeQuery();
    while (rs.hasNext())
    // load your data into a data structure to pass back.
    rs.close();
    statement.close();Let me know if that works. - MOD

  • Weird problem with mysql query and data table buttons !!!!

    Hi,
    I'm using jsc 2 update 1 on windows and mysql 4.1 . I have a page with a data table. One column of the data table contains "Details" buttons.
    Source query for the table is :
    SELECT tbl_tesserati.idtbl_tesserati idTesserato,
    tbl_tesserati.num_tessera,
    tbl_tesserati.nome,
    tbl_societa.codice_meccanografico
    FROM tbl_tesserati
    INNER JOIN tbl_rel_tesserato_discipline_societa ON tbl_tesserati.idtbl_tesserati = tbl_rel_tesserato_discipline_societa.id_tesserato
    INNER JOIN tbl_cariche ON      tbl_rel_tesserato_discipline_societa.id_carica = tbl_cariche.idtbl_cariche
    INNER JOIN tbl_qualifiche ON      tbl_rel_tesserato_discipline_societa.id_qualifica = tbl_qualifiche.idtbl_qualifiche
    INNER JOIN tbl_discipline ON      tbl_rel_tesserato_discipline_societa.id_disciplina = tbl_discipline.idtbl_discipline
    INNER JOIN tbl_societa ON      tbl_rel_tesserato_discipline_societa.id_societa = tbl_societa.idtbl_societa
    LEFT JOIN tbl_province ON tbl_societa.provincia_sede_sociale = tbl_province.idtbl_province
    LEFT JOIN tbl_comuni ON tbl_societa.comune_sede_sociale = tbl_comuni.idtbl_comuni
    LEFT JOIN tbl_rel_tesserato_discipline_praticate ON tbl_rel_tesserato_discipline_praticate.tessera_id=
    tbl_rel_tesserato_discipline_societa.idtbl_rel_tesserato_discipline
    LEFT JOIN tbl_discipline_praticate ON tbl_discipline_praticate.idtbl_disciplina_praticate=tbl_rel_tesserato_discipline_praticate.disciplina_praticata_id
    WHERE
    tbl_tesserati.cognome LIKE ?
    AND tbl_tesserati.nome LIKE ?
    AND tbl_rel_tesserato_discipline_societa.id_societa LIKE ?
    AND tbl_tesserati.idtbl_tesserati LIKE ?
    AND tbl_cariche.idtbl_cariche LIKE ?
    AND tbl_qualifiche.idtbl_qualifiche LIKE ?
    AND tbl_tesserati.data_nascita >= ?
    AND tbl_tesserati.data_nascita<= ?
    AND tbl_discipline.idtbl_discipline LIKE ?
    AND codice_affiliazione LIKE ?
    AND tbl_societa.denominazione LIKE ?
    AND YEAR(tbl_rel_tesserato_discipline_societa.data_scadenza) LIKE ?
    AND (tbl_province.nome LIKE ? OR tbl_province.nome IS NULL)
    AND ( tbl_comuni.nome LIKE ? OR tbl_comuni.nome IS NULL)
    The tbl_tesserati.data_nascita is a mysql date field.
    The click event handler code for the "Details" Button is:
    public String btnModificaTesserato_action() {
            try{
                TableRowDataProvider rowData= (TableRowDataProvider)getBean("currentRowTesserati");
                getRequestBean1().setId_tesserato((Long)rowData.getValue("idTesserato"));          
            } catch(Exception ex) {
                log("errore nella query",ex);
            return "dettaglioTesseratoSocieta";
        }When i run the project and open the page the table is correctly rendered and populated with some rows. But when i click on details button nothing happens, the page is simply reloaded.
    If i set a breakpoint in the code line   TableRowDataProvider rowData= (TableRowDataProvider)getBean("currentRowTesserati");the debbuger does not stop the code execution ! As if the button was never clicked!
    I tried to modify the source query to :
    SELECT tbl_tesserati.idtbl_tesserati idTesserato,
    tbl_tesserati.num_tessera,
    tbl_tesserati.nome,
    tbl_societa.codice_meccanografico
    FROM tbl_tesserati
    INNER JOIN tbl_rel_tesserato_discipline_societa ON tbl_tesserati.idtbl_tesserati = tbl_rel_tesserato_discipline_societa.id_tesserato
    INNER JOIN tbl_cariche ON      tbl_rel_tesserato_discipline_societa.id_carica = tbl_cariche.idtbl_cariche
    INNER JOIN tbl_qualifiche ON      tbl_rel_tesserato_discipline_societa.id_qualifica = tbl_qualifiche.idtbl_qualifiche
    INNER JOIN tbl_discipline ON      tbl_rel_tesserato_discipline_societa.id_disciplina = tbl_discipline.idtbl_discipline
    INNER JOIN tbl_societa ON      tbl_rel_tesserato_discipline_societa.id_societa = tbl_societa.idtbl_societa
    LEFT JOIN tbl_province ON tbl_societa.provincia_sede_sociale = tbl_province.idtbl_province
    LEFT JOIN tbl_comuni ON tbl_societa.comune_sede_sociale = tbl_comuni.idtbl_comuni
    LEFT JOIN tbl_rel_tesserato_discipline_praticate ON tbl_rel_tesserato_discipline_praticate.tessera_id=
    tbl_rel_tesserato_discipline_societa.idtbl_rel_tesserato_discipline
    LEFT JOIN tbl_discipline_praticate ON tbl_discipline_praticate.idtbl_disciplina_praticate=tbl_rel_tesserato_discipline_praticate.disciplina_praticata_id
    WHERE
    tbl_tesserati.cognome LIKE ?
    AND tbl_tesserati.nome LIKE ?
    AND tbl_rel_tesserato_discipline_societa.id_societa LIKE ?
    AND tbl_tesserati.idtbl_tesserati LIKE ?
    AND tbl_cariche.idtbl_cariche LIKE ?
    AND tbl_qualifiche.idtbl_qualifiche LIKE ?
    AND tbl_tesserati.data_nascita >= ?
    OR tbl_tesserati.data_nascita<= ?
    AND tbl_discipline.idtbl_discipline LIKE ?
    AND codice_affiliazione LIKE ?
    AND tbl_societa.denominazione LIKE ?
    AND YEAR(tbl_rel_tesserato_discipline_societa.data_scadenza) LIKE ?
    AND (tbl_province.nome LIKE ? OR tbl_province.nome IS NULL)
    AND ( tbl_comuni.nome LIKE ? OR tbl_comuni.nome IS NULL)
    Using this query everything works well !! The click handler works and the debugger too !!
    I changed only the AND in OR !!!
    I also tried to change mysql-x-x-connector driver but without solving my problem.
    Can someone help me ?
    Thanks
    Giorgio

    You'll find that it is more to do with the way MySql deals with dates than anything else! Depending on how your date field is setup, then try using a BETWEEN statement for those 2 lines in your first query e.g.
    AND ( tbl_tesserati.data_nascita BETWEEN ? AND ?)
    The date column needs to be in the ISO format to work. If you examine your second query output, you might discover that the output is only going to refer to one parameter (probably the OR one). Did you manage to view the output logs from the application server? You would have got an idea from there with a message like stating a conversion error'.
    Alternatively, you could try using the to_days() function and convert it directly to a number which would be a lot easier to deal with. For example:
    AND to_days(tbl_tesserati.data_nascita >= ? )
    AND to_days( tbl_tesserati.data_nascita<= ? )
    Or try the BETWEEN version with to_days() and see what you get.
    More info about date formatting (v5) here:
    http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_to-days
    Before I forget, sometimes you may need to treat dates as Strings rather 'Long' as you did.
    As a matter of interest, did you try your query in a different piece of software?
    If my queries are a little more complicated, I tend to try MySql queries out in the free MySql query browser and also double check in another to verify certain issues. I found it easier to develop SQL in a seperate program then import the final version to JSC making the required modifications for parameters.
    Message was edited by:
    aerostra

  • Need help with MySQL Query...Again

    Ok so I get this error when I enter "springfield" and "MA" for the city and state.
    This server program accepts either a 'zipcode' or 'city, state' depending on the choice # passed to it.
    I just need to be able to perform the query.
    Thanks!!
    java.sql.SQLException: Unknown column 'springfield' in 'where clause'
    Error4
         at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2975)
         at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1600)
         at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1695)
         at com.mysql.jdbc.Connection.execSQL(Connection.java:3020)
         at com.mysql.jdbc.Connection.execSQL(Connection.java:2949)
         at com.mysql.jdbc.Statement.executeQuery(Statement.java:959)
         at ThreadConnect.run(ZipcodeServer.java:84)Here is my code:
    import java.sql.*;
    import java.io.*;
    import java.net.*;
    public class ZipcodeServer {
         static void runServer() {
              ServerSocket server;
              Socket connection;
              try {
                   System.out.println("Creating Server Socket " + 5000 + " . . . ");
                   server = new ServerSocket(5000);
                   System.out.println("SUCCESS!!!");
                   while (true) {
                        System.out.println("Waiting for connection.");
                        connection = server.accept();
                        System.out.println("Done");
                        ThreadConnect t = new ThreadConnect(connection);
                        t.start();
              } catch (IOException e) {
                   System.out.println("Error5");
                   e.printStackTrace();
         public static void main(String args[]) {
              ZipcodeServer.runServer();
    class ThreadConnect extends Thread {
         Socket connection;
         DataOutputStream output;
         DataInputStream input;
         ThreadConnect(Socket x) {
              connection = x;
         public void run() {
              try {
                   input = new DataInputStream(connection.getInputStream());
                   output = new DataOutputStream(connection.getOutputStream());
                   try {
                        int choice = input.readInt();
                        String city, state;
                        int zipcode;
                        if (choice == 1) {
                             int zc = input.readInt();
                             DatabaseConnection.connect();
                             DatabaseConnection.rs = DatabaseConnection.s
                                       .executeQuery("SELECT City,State FROM Zipcodes "
                                                 + "WHERE ZipCode = " + zc);
                             while (DatabaseConnection.rs.next()) {
                                  state = DatabaseConnection.rs.getString("State");
                                  output.writeUTF(state);
                                  output.flush();
                                  city = DatabaseConnection.rs.getString("City");
                                  output.writeUTF(city);
                                  output.flush();
                        } else if (choice == 2) {
                             city = input.readUTF();
                             state = input.readUTF();
                             DatabaseConnection.connect();
                             DatabaseConnection.rs = DatabaseConnection.s
                                       .executeQuery("SELECT ZipCode FROM Zipcodes "
                                                 + "WHERE City = " + city + " AND State = "
                                                 + state);
                             while (DatabaseConnection.rs.next()) {
                                  zipcode = DatabaseConnection.rs.getInt("ZipCode");
                                  output.writeInt(zipcode);
                                  output.flush();
                   } catch (Exception e) {
                        System.out.println("Error4");
                        e.printStackTrace();
                   } finally {
                        DatabaseConnection.close();
              } catch (IOException e) {
                   System.out.println("Error3");
                   e.printStackTrace();
    class DatabaseConnection {
         static Connection con;
         static Statement s;
         static ResultSet rs;
         static String driver = "com.mysql.jdbc.Driver";
         static String url = "jdbc:mysql://***.****.******/***";
         static String user = "*******";
         static String password = "********";
         static void connect() {
              try {
                   Class.forName(driver).newInstance();
                   System.out.println("Loaded Driver");
                   con = DriverManager.getConnection(url, user, password);
                   System.out.println("Connected to database\n");
                   con.setAutoCommit(false);
                   s = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                             ResultSet.CONCUR_READ_ONLY);
              } catch (Throwable e) {
                   System.out.println("Error2");
                   e.printStackTrace();
         static void close() {
              try {
                   rs.close();
                   s.close();
                   con.close();
                   System.out.println("\nDisconnected From Database");
              } catch (Throwable e) {
                   System.out.println("Error1");
                   e.printStackTrace();
    }

    R.Baldwin7 wrote:
    I tried it. Still getting the same error.
    Code no looks like:
    else if (choice == 2) {
                             city = input.readUTF();
                             state = input.readUTF();
                             DatabaseConnection.connect();
                             PreparedStatement ps = DatabaseConnection.con.prepareStatement("SELECT ZipCode FROM Zipcodes "
                                       + "WHERE City = " + city + " AND State = "
                                       + state);
                             DatabaseConnection.rs = ps.executeQuery();
                             while (DatabaseConnection.rs.next()) {
                                  zipcode = DatabaseConnection.rs.getInt("ZipCode");
                                  output.writeInt(zipcode);
                                  output.flush();
    Read the API docs and the JDBC Tutorials for the proper way to use a PreparedStatement. It may "work" to add the quotes, but it is definately not the right way to do it. What happens if the city entered contains an apostrophe? Your statement will be broken again. Like I said, use a PreparedStatement and use it right.

  • Having alot of trouble with a query

    Hey, I'm having trouble with a query for an assignment. The questions states
    Find the name of the highest earning employee in each location, excluding managers, salespeople and the president
    The problem I'm having is that my query returns the highest earning employee from each location perfectly, but one of those returned is a salesperson, so the next highest earning person in that location should be returned.
    We are also not allowed to create a temporary table
    Here's my code so far
    select
    e.first_name,
    e.last_name,
    e.salary,
    l.regional_group
    from employee e
    inner join department d
    on d.department_id = e.department_id
    inner join location l
    on l.location_id = d.location_id
    where e.salary = (select max(e2.salary) from employee e2
    inner join department d2
    on d2.department_id = e2.department_id
    inner join location l2
    on l2.location_id = d2.location_id
    where l2.location_id = l.location_id
    and e.job_id !=672;
    the job_id refers to what job title they have
    and here's the schema below
    Schema
    Any help you could give me on this would be fantastic as I have been pulling my hair out over this for the last day.
    Edited by: 837562 on 17-Feb-2011 02:14

    Maybe you can try the below:
    with job_location as
    select 1 location_id, 'loc1' regional_group from dual
    union
    select 2 location_id, 'loc2' regional_group from dual
    department as
    select 1 department_id, 'dept1' dept_name, 1 location_id from dual
    union
    select 2 department_id, 'dept2' dept_name, 2 location_id from dual
    job_FUNCTION as
    select 1 job_id, 'MANAGER' job_function from dual
    UNION
    select 2 job_id, 'SALES' job_function from dual
    UNION
    select 3 job_id, 'PRESIDENT' job_function from dual
    UNION
    select 4 job_id, 'REST_1' job_function from dual
    UNION
    select 5 job_id, 'REST_2' job_function from dual
    employee as
    select 1 employee_id, 'a' last_name, 100 salary, 1 department_id, 4 JOB_ID from dual union
    select 2 employee_id, 'b' last_name, 200 salary,1, 5 from dual union
    select 3 employee_id, 'c' last_name, 300 salary,1, 2 from dual union
    select 4 employee_id, 'd' last_name, 400 salary,1, 2 from dual union
    select 5 employee_id, 'e' last_name, 500 salary,2, 3 from dual union
    select 6 employee_id, 'f' last_name, 600 salary,2, 3 from dual union
    select 7 employee_id, 'g' last_name, 700 salary,2, 4 from dual union
    select 8 employee_id, 'h' last_name, 800 salary,2, 4 from dual
    select
    regional_group, employee_id, max_salary
    from
    select e.regional_group, b.department_id, employee_id, salary, max(b.salary) over (partition by b.department_id order by b.department_id) max_salary
    from
    employee b,
    job_function c,
    department d,
    job_location e
    where
    b.job_id = c.job_id and
    b.department_id = d.department_id and
    e.location_id = d.location_id and
    c.job_id not in (1,2,3) 
    ) where salary = max_salary;
    "REGIONAL_GROUP"     "EMPLOYEE_ID"     "MAX_SALARY"
    "loc1"     "2"     "200"
    "loc2"     "8"     "800"

  • Trouble with query on Reports

    Hi,
    I am having trouble with a query which results from a join of 4 tables, of which, one table is shortened by grouping it along one column.
    for example
    A join B join C join (D grouped by D.S)
    In MS Access I had used a separate query to represent this and done a join with the remaining tables to generate my report.
    Any one has any idea about how this can be done using just one query, or any way I can store the sub-result elsewhere like in Access.
    Thanks!

    Not usre this is a reports issue, but:
    I think you are trying to select from tables and queries in one.
    IN your SQL statement try
    SELECT data,etc
    FROM
    A,
    B,
    C
    , (select distinct S from D) Q_D
    where
    A join B join C join Q_D
    Note that I don't think you can use sub queries like this in Access

  • I am having trouble with app updates on my iOS 5 iPhone never getting beyond the "waiting" state.

    I am having trouble with app updates on my iOS 5 iPhone never getting beyond the "waiting" state. I have tried signing out/in of my account, rebooting and removing/re-installing the apps.  This started shortly after going to iOS 5 but I am not certain if that is related.  All updates that I try now are stuck in "waiting".  I also tried removing the apps and then installing via iTunes desktop sync with no improvement.  The only thing that I have not tried so far is a restore to a prior iPhone backup.  I have not been able to find anything to indciate what the updates on waiting on.  There is plenty of space on the iPhone (16gb available).  Any suggestions on what to try next? 

    Hello there, Missy.
    First thing I would recommend is to check your downloads queue to make sure there is not an interrupted download per the following Knowledge Base article:
    iTunes: How to resume interrupted iTunes Store downloads
    http://support.apple.com/kb/HT1725
    If your download was interrupted using your iPhone, iPad, or iPod touch
    1. From the Home screen, tap the iTunes app.
    2. For iPhone or iPod touch, tap More > Downloads. For iPad, tap Downloads.
    3. Enter your account name and password if prompted.
    4. Tap the blue download arrow to resume.
    If you can't complete the download on your iOS device, you can download it in iTunes on your Mac or PC and then sync it to your iOS device. You can also transfer purchases from your iPhone, iPad, or iPod to a computer.
    For Apps, you can also try tapping on the application icon to resume the download, as outline in this featured discussion:
    App updates won't download on my...: Apple Support Communities
    https://discussions.apple.com/thread/4111336
    Try tapping the App, so that it changes to Paused instead of Waiting, then tap it again to resume the install.
    Make sure you don't have any paused downloads in other apps either, like the App Store or iTunes Store.
    If that doesn't do it, try resetting or restoring the iPhone.
    via whatheck
    Thanks for reaching out to Apple Support Communities.
    Cheers,
    Pedro.

  • Invalid state in SQL query for a function that was created with no errors.

    SQL> CREATE OR REPLACE FUNCTION overlap(in_start1 IN TIMESTAMP, in_end1 IN TIMESTAMP, in_start2 IN TIMESTAMP, in_end2 IN TIMESTAMP) RETURN NUMBER
    2 IS
    3
    4 BEGIN
    5 IF (in_start1 BETWEEN in_start2 AND in_end2 OR in_end1 BETWEEN in_start2 AND in_end2 OR in_start2 BETWEEN in_start1 AND in_end1) THEN
    6 RETURN 0;
    7 ELSE
    8 RETURN 1;
    9 END IF;
    10 END;
    11 /
    Function created.
    SQL> show errors;
    No errors.
    SQL>
    SQL> SELECT * FROM tbl where overlaps(current_time,current_time+1,current_time-1,current_time+2) = 0;
    SELECT * FROM tbl where overlaps(current_time,current_time+1,current_time-1,current_time+2) = 0
    ERROR at line 1:
    ORA-06575: Package or function OVERLAPS is in an invalid state
    I do not understand why overlaps is returned as in invalid state in the query, when it was created with no errors earlier. Could anyone help me?

    Marius
    Looking at the logic you are trying to create it looks like you are looking for overlapping time periods.
    Consider two date/time ranges:
    Range 1 : T1 - T2
    Range 2 : T3 - T4
    Do they overlap?
    1) No: T1 < T4 (TRUE)  T2 > T3 (FALSE)
    T1 --- T2
               T3 --- T4
    2) Yes: T1 < T4 (TRUE)  T2 > T3 (TRUE)
    T1 ---------- T2
               T3 --- T4
    3) Yes: T1 < T4 (TRUE)  T2 > T3 (TRUE)
    T1 -------------------- T2
               T3 --- T4
    4) Yes: T1 < T4 (TRUE)  T2 > T3 (TRUE)
                   T1 ----- T2
               T3 --- T4
    5) Yes: T1 < T4 (TRUE)  T2 > T3 (TRUE)
               T1 --- T2
           T3 ------------ T4
    5) No: T1 < T4 (FALSE) T2 > T3 (TRUE)
                    T1 --- T2
           T3 --- T4Answer: Yes they overlap if:
    T1 < T4 AND T2 > T3
    So you can code the logic in your SQL as simply:
    SELECT *
    FROM tbl
    WHERE range1_start < range2_end
    AND    range_1_end > range2_startIf you go around implementing PL/SQL functions for simple logic that can be achieved in SQL alone then you cause context switching between the SQL and PL/SQL engines which degrades performance. Wherever possible stick to just SQL and only use PL/SQL if absolutely necessary.

  • I have a Lucid 2 LG.  I have been having trouble with insuffient storage.  I have a 8G phone and have spent hours with Tier 2 tech trying to move info from the internal storage to the SD card with no luck,  When I go to storage in the settings it states t

    I have a Lucid 2 LG.  I have been having trouble with insuffient storage.  I have a 8G phone and have spent hours with Tier 2 tech trying to move info from the internal storage to the SD card with no luck,  When I go to storage in the settings it states that over 4 gigs is for Misc?  System data takes up over 4 gigs.  No one can tell me what system data consist of.  So My question is does anyone know what system data is?  I am assuming I have a 8 gigphone but can only use 4 gigs???

    System data is the OS or operating system.  That is where the recovery stays separated from the rest of the storage so that it doesn't get corrupted.  It is not accessible and non-movable.

Maybe you are looking for

  • Java SDK ME on 64bit Vista?

    I'm trying to pick up some programming skills in Java so that I can make apps for my phone, I require Java SDK ME to do so. I've seen a lot of people saying that Java SDK ME won't work on 64bit Vista and they're right, it doesn't. However, some peopl

  • Sorting by size in lightroom

    From Lightroom's first beta version I have been disappointed that there is no way to sort in the library module by image file size. Sorting by size is so common in computer programs. The mac operating system windows have had this option as far back a

  • Item-level Permissions availabe in list advance setting not working.

    Hi,      Recently i had an requirement of maintaining item level permission. My requirement was that whenever an item is created in list, it should be created with uniqure permission. I know how to do it by writing custom code, but i don't want to do

  • Toolbox won't  maximize        PHOTOSHOP CS2

    The toolbox remains minimized. The healing tool remains selected. I've tried the following: 1) Reopened program 2) Restarted CPU 3) Reloaded software Suggestions appreciated.

  • Rgd Function Module

    Hi We have a function module in which we call a BAPI Function Module and we need to  declare same  parameter while passing values to in and out of function module I have a case where Example call function 'bapi_create1' Table schlx = bapi... but in B