Can I loop a sql query???

Hi,
I have an array that has x number of values. I want to run a
sql statement x number of times using the next array value each
time.
Basically I have a recordset that displays results based on a
search. The result of the search is a list of names, the trouble is
for reasons beyond my control the names are in a single db field as
"FirstLast". I want to take this value and match it up to another
table that has the first and last names in separate fields. So far
I have extracted the results from the first recordset using a while
loop, the resulting array is called $name_search :
mysql_select_db($database_nancy, $nancy);
$query_search = "SELECT artist FROM images WHERE caption LIKE
'%$keyword%' OR piece_name LIKE '%$keyword%' OR show_title LIKE
'%$keyword%' GROUP BY artist";
$search = mysql_query($query_search, $nancy) or
die(mysql_error());
$totalRows_search = mysql_num_rows($search);
$name_search = array();
while(list($artist) = mysql_fetch_row($search)) {
$name_search[] = $artist;
I now want to take the values of the $name_search array and
run a SELECT statement on table2 for each value and display the
results. Could a foreach loop handle that ? Using php/mysql

well, I´ve been thinking about that, and the only idea I
had was using a subquery for this, like:
<?php
$query_subsearch="SELECT CONCAT(firstname, ' ', lastname) AS
fullname FROM other_table WHERE lastname LIKE
'".%$search['artist']%."'";
$subsearch = mysql_query($query_subsearch, $nancy) or
die(mysql_error());
$row_subsearch = mysql_fetch_assoc($search);
$totalRows_subsearch = mysql_num_rows($subsearch);
?>
<?php do { ?>
- <?php echo $row_subsearch['fullname']; ?>
<br>
<?php } while ($row_subsearch =
mysql_fetch_assoc($subsearch)); ?>
<?php
mysql_free_result($subsearch);
?>
This example might or might not work, but introducing
subqueries as such is possible -- there might be other options
which don´t require matching against another table at all, but
please let me know, if...
1. you need that for displaying purposes alone ?
2. the "format" of the names is always identical both in the
artist field
(e.g. JohnDoe) and the other table
(John Doe) -- in particular: will the "last name" always
start with an uppercase letter ?
If yes, I´ve been thinking about applying a case
sensitive regular expression on the "artist" field alone which
will...
a) detect the last lower case letter that´s preceeding
the following Upper case letter and capture each element into a
backreference
(see the $pattern variable), and
b) add a hardcoded space in between those backreferences
(see the $replacement variable).
If this approach should match the 2nd. "last name always
starts with an Upper Case letter" requirement, give it a try using
the following example
<?php
$test = "JohnDoe";
$pattern = '/([a-z])([A-Z])/';
$replacement = '${1} ${2}';
$test = preg_replace($pattern,$replacement,$test);
?>
<?php
echo $test;
?>
if not, I actually don´t have any other idea at the
moment ;-)

Similar Messages

  • Can I put a SQL query into a bind variable and then use it to output report

    Hi,
    Can I put a SQL query into a bind variable and then use it to output report?
    I want to create a report and an item "text area" (say P1_TEXT) which can let user to input a SQL query(they are all technical users and knows SQL very well). Then, I use a bind variable (that text area) to store the SQL statement. Then, I add a submit button and I want to use the following to output the report:
    select * from (:P1_TEXT);
    Do you think it is possible to do that? Any known limitations for APEX in this area?
    Thanks a lot,
    Angela

    You can, but make sure it's what you really want to do. Make sure you are VERY familiar with SQL Injection. Most people who know what it is, go out of their way to prevent SQL Injection. You're going out of your way to allow it.
    You can try using &P1_TEXT. instead of bind variable syntax. Bind variables are one of the best ways to prevent SQL Injection, which is why it's not working for you.
    Once again, I strongly urge you to consider the implications of your app, but this suggestion should get it working.
    Tyler

  • Can anybody provide the SQL query to find the files uploaded in a particular folder?

    Hi All,
    Can anybody provide the SQL query to find the documents (document name) uploaded in a particular folder? While clicking on folder in
    GUI I'm hitting the Timeout error. I would like to find the files uploaded into this folder from SQLPLUS.
    Any help is greatly appreciated.
    With best regards,
    Nevin

    Nevin,
    Be great if we could know the version of Portal. For Rel. 1, here's the query
    select id,masterthingid from wwv_things
    where siteid = &site
    and cornerid = &corner
    &site - Content Area id
    &corner - Folder id
    if you don't know the folder id, use
    select id from wwv_corners where siteid = &site
    and name = &folder
    Hope this helps. I have run into this situation before. Usually, the culprits were
    one of the following:
    1. Junk Characters in description of item (caused due to Copy-Paste)
    2. Special Characters in the File name
    Hi All,
    Can anybody provide the SQL query to find the documents (document name) uploaded in a particular folder? While clicking on folder in
    GUI I'm hitting the Timeout error. I would like to find the files uploaded into this folder from SQLPLUS.
    Any help is greatly appreciated.
    With best regards,
    Nevin

  • Can Portal Report from SQL Query use where column IN (:bind_variable)

    I would like to create a portal report from sql query with IN (:bind_variable) in the where clause. The idea is that the user would enter comma-separated or comma-quote-separated values for the bind_variable. I have tried this several ways but nothing seems to work. Can this be done?
    Trenton

    Hi,
    Which version of portal are you using. This is a bug. It has been fixed in 30984.
    Thanks,
    Sharmila

  • Can't  write right sql query by two tables

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

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

  • Can You Explain This SQL Query - Inline View Included

    The query is taken from "Oracle Database 10g: SQL Fundamentals II" page 3-7 (chapter 3)
    I do not fully understand the following query:
    SELECT a.last_name, a.salary, a.department_id, b.salavg
    FROM   employees a, (SELECT   department_id,
    AVG(salary) salavg
    FROM     employees
    GROUP BY department_id) b
    WHERE  a.department_id = b.department_id
    AND    a.salary > b.salavg;
    The inline view can return several records. Can you please tell me in step by step how does this work. I understand the concept of join tables and aliases, etc. I just need to know the mechanism of this code.
    Thanks

    user11164565 wrote:
    The query is taken from "Oracle Database 10g: SQL Fundamentals II" page 3-7 (chapter 3)
    I do not fully understand the following query:
    SELECT a.last_name, a.salary, a.department_id, b.salavg
    FROM   employees a, (SELECT   department_id,
    AVG(salary) salavg
    FROM     employees
    GROUP BY department_id) b
    WHERE  a.department_id = b.department_id
    AND    a.salary > b.salavg;
    The inline view can return several records. Can you please tell me in step by step how does this work. I understand the concept of join tables and aliases, etc. I just need to know the mechanism of this code.
    The query is returning the last name, salary , department and average salary of all the departments where salary is greater than the average salary.
    HTH
    Aman....

  • How Can I Make This Sql Query To Load Data Correctly (sql server)?

    Hi guys
    I have a datagridview where the third column is a custom column with all days
    of a month. It takes data with a query who distinct the column Improve.
    Here is the code :
    Private Sub fill_impro()
    dgImprove.Rows.Clear()
    Try
    Dim i As Integer = 0
    Dim query As String = "SELECT Improve,Price,Active,Idate FROM (SELECT Improve,Price,Active,Idate, ROW_NUMBER() OVER (PARTITION BY Price ORDER BY Price) AS rn FROM tblImprove) tmp WHERE rn = 1"
    cmd = New SqlCommand(query, clsMSSQL.con)
    myDR = cmd.ExecuteReader
    If myDR.HasRows Then
    While myDR.Read
    dgImprove.Rows.Add()
    dgImprove.Rows(i).Cells(0).Value = myDR.GetDecimal(myDR.GetOrdinal("Price"))
    dgImprove.Rows(i).Cells(1).Value = myDR.GetString(myDR.GetOrdinal("Improve"))
    Dim myday As Integer = DatePart(DateInterval.Day, myDR.GetValue(myDR.GetOrdinal("Idate")))
    dgImprove.Rows(i).Cells(myday + 1).Value = myDR.GetInt32(myDR.GetOrdinal("Active"))
    i = i + 1
    End While
    End If
    myDR.Close()
    Catch ex As Exception
    MsgBox(ex.Message, MsgBoxStyle.Critical, "Σφάλμα")
    End Try
    End Sub
    And here is the result :
    http://i60.tinypic.com/28gwf83.jpg
    The column Active value is 1.
    The problem is that column Active values are missing (red values in image).
    How can i fix that ?
    Thanks in advance

    try like this
    Dim Price As Decimal
    Dim improve As String = String.Empty
    While myDR.Read
    Dim myday As Integer = DatePart(DateInterval.Day, myDR.GetValue(myDR.GetOrdinal("Idate")))
    If Not (myDR.GetDecimal(myDR.GetOrdinal("Price")) = Price And myDR.GetString(myDR.GetOrdinal("Improve")) = improve) Then
    i += 1
    dgimprove.Rows.Add()
    dgimprove.Rows(i).Cells(0).Value = myDR.GetDecimal(myDR.GetOrdinal("Price"))
    dgimprove.Rows(i).Cells(1).Value = myDR.GetString(myDR.GetOrdinal("Improve"))
    Price = myDR.GetDecimal(myDR.GetOrdinal("Price"))
    improve = myDR.GetString(myDR.GetOrdinal("Improve"))
    End If
    dgimprove.Rows(i).Cells(myday + 1).Value = myDR.GetInt32(myDR.GetOrdinal("Active"))
    End While
    and change your sql statement to just
    SELECT Improve,Price,Active,Idate FROM tblImprove WHERE Active = 1

  • How can I create an sql query updateable report

    Seems as though after upgrading our APEX version I no longer have the option to create an updateable report. Some of my old updateable reports seem to be working fine but some will not update after I click my submit button. AT first they just refreshed the page and ignored my changes to the data in the text field. After tinkering with the non working region, now I get a ORA-20001 current version of data in database has changed etc.
    HELP!

    Hi,
    OK - first, you can still create an Updatable Report. When you create a new report, select the Wizard Report option and follow the prompts. When the report has been created you can then switch it to be updatable. I don't know why it has been done this way, but that works.
    Second, on the reports that return that error, do you have any columns set a Standard Report Column? I have found that you need to include ALL columns in the data being submitted, even if that means you have to create a second instance of a column in your SQL statement and then make one of the columns Hidden. For example, if you created a Tabular Form using the wizard on the EMP table, you get EMPNO and EMPNO_DISPLAY, with EMPNO hidden. You would need to do the same for any column not being edited by the user. Something similar may also happen if you have made any of the INPUT items readonly or disabled as these are not submitted by the browser.
    Andy

  • Can u help in SQL Query

    HI,
    I need to insert some of the data from Table I to Table O by doing before i need to group five fields based on this group i should insert Table I fields. How can i solve this query? pls help.
    Thanks in Advance.

    in case you are not doing a group by on all columns you have to use a group-function on those fields not included in group by clause, i.e. :
    insert into test (a,b,c,d,e,f)
       select a,b,c, max(d), min(e), sum(f)
          from facts
         group by a,b,c

  • How Can I Make This Sql Query To Load Data Correctly (sql server 2014)?

    Hi guys
    I have a datagridview where the third column is a custom column with all days
    of a month. It takes data with a query who distinct the column Improve.
    SELECT Improve,Price,Active,Idate FROM (SELECT Improve,Price,Active,Idate, ROW_NUMBER() OVER (PARTITION BY Improve ORDER BY Improve) AS rn FROM tblImprove) tmp WHERE rn = 1
    And here is the result :
    http://i60.tinypic.com/28gwf83.jpg
    The column Active value is 1.
    The problem is that column Active values are missing (red values in image).
    How can i fix that ?
    Thanks in advance
     

    Hi, 
    Maybe you can try below code, I have changed the order by of the row_number(). Therefore it will sort on the date, and you will get the first date icm with improve cell. If this is not what you are looking for, please explain what the output should be. 
    SELECT Improve,Price,Active,Idate
    FROM
    SELECT Improve,Price,Active,Idate, ROW_NUMBER() OVER (PARTITION BY Improve ORDER BY ldate) AS rn
    FROM tblImprove
    ) tmp WHERE rn = 1
    Regards, 
    Reshma
    Please Vote as Helpful if an answer is helpful and/or Please mark Proposed as Answer or Mark As Answer when question is answered

  • Can we execute the SQL query mannually

    hi,
    an error occurs when the drill down from higher to lower level as
    " Odbc driver returned an error (SQLExecDirectW).
    + Error Details
    Error Codes: OPR4ONWY:U9IM8TAC:OI2DL65P:OI2DL65P
    State: HY000. Code: 10058. [NQODBC] [SQL_STATE: HY000] [nQSError: 10058] A general error has occurred. [nQSError: 27005] Unresolved column: "CA". (HY000)"
    how can we solve this problem...not only for this one report iam getting to number of reports.
    plz plz help to solve this problem.
    Thanks in advance.

    Increase the log level for the user you're using to do the tests to at least 2 (Admin Tool -> Manage -> Security -> User -> Logging Level).
    The run the report in question. Either check the logs through the web interface (Settings -> Administration -> Manage Sessions -> View Log) or just go to the server and check the NQQuery.log.
    Cheers,
    Christi@n

  • How can I use the Rownum/Customized SQL query in a Mapping?

    Hi,
    * I need to use a Rownum for populating one of the target field? How to create a mapping with Rownum?
    * How can I use an Dual table in OWB mapping?
    * Can I write Customized SQL query in OWB? How can I achieve this in a Mapping?
    Thanks in Advance
    Kishan

    Hi Niels,
    As I'm sure you know, the conundrum is that Reports doesn't know how many total pages there will be in the report until it is all done formatting, which is too late for your needs. So, one classical solution to this problem is to run the report twice, storing the total number of pages in the database using a format trigger, and throwing away the output from the first run when you don't know the total number of pages.
    Alternatively, you could define a report layout so that the number of pages in the output is completely predictable based upon, say, the number of rows in the main query. E.g., set a limit of one, two, ... rows per page, and then you'll know how many pages there will be simply because you can count the rows in a separate query.
    Hope this helps...
    regards,
    Stewart

  • Can we change/Modify BI server generated Sql query and run to fetch data

    Hi,
    My client is saying that there is an option to modify bi server generated sql query to fetch data from source.
    question:As a request is made in presentation services, A dynamic sql query is generated and fetches data from source. all this is loggedin Nqlquery log..well can we change/modify the sql query generated and run modified sql query to fetch data from source. ., if so how? if not why?
    Thanks in advance
    Edited by: user10794468 on Jun 16, 2009 6:29 PM
    Edited by: user10794468 on Aug 12, 2009 6:58 PM

    Thank you so much for your reply..
    ..Can we also modify sql query generated by bi server to fetech data. the query's which we see in query log file..

  • What can be the SQL Query for this requirement ?

    Hi,
    I have a table with fields like this:
    ID DESC PARENT
    01 ABC 02
    02 ABC1 01
    03 ABC2 01
    04 ABC4 02
    In the above table PARENT column refers to ID column , but actually in SQL query i want to have ID, DESC , and PARENTDESC (i.e., desc value of the corresponding ID)
    Actual output that i need is
    select ID , DESC , ?? from table where ID=someValue . Now if i provide ID=01 then output should be like this:
    ID DESC PARDESC
    01 ABC ABC1
    Can anyone help what can be the required sql query ?
    Edited by: bootstrap on Apr 29, 2011 6:15 AM

    SELECT T1.ID, T1.DESC, T2.DESC
    FROM TABLEA T1, TABLEA T2
    WHERE T1.ID='01'
    AND T2.ID = T1.PARENT;

  • Looping within table query

    Hi all,
    I've run into a problem... Is there anyway where we can do looping in a table in a single SQL query. Basically the scenario is like this :
    *Consider a table with sample data as follows:
    SQL> select * from TEST2;
    EMPNO JOB REL_DT
    1 SALESMAN 01-NOV-06
    2 MANAGER 01-NOV-06
    1 SALESMAN 01-OCT-06
    2 MANAGER 01-OCT-06
    1 CLERK 01-SEP-06
    *Basically the table has a relationship start date i.e. b/w an Employee and a job title.
    *Is there anyway to know the previous job title held by an employee. Basically the logic is as follows:
    get the max(rel_dt) and get the empno.
    for the same empno. traverse the table for rel_dt<max(previous rel_dt) and where job<>previous job.
    Basically this involves looping within the table to find a previous job. This can be done with a procedure. But is there a way we can construct a single SQL query to meet this requirement?
    Thanks in advance :)

    Woops... Okay.. there's a slight problem .. :(
    consider the table below with sample data:
    SQL> select * from test2;
    EMPNO JOB REL_DT
    1 SALESMAN 01-NOV-06
    2 MANAGER 01-NOV-06
    1 SALESMAN 01-OCT-06
    2 MANAGER 01-OCT-06
    1 CLERK 01-SEP-06
    1 HOUSEKEEPING 23-SEP-06
    How do I select the first date that empno=1 was a 'SALESMAN'? In the above table, he was a 'SALESMAN' first on '01-OCT-06' and was 'HOUSEKEEPING' before this?
    *Basically how do i retrieve empno=1 his first REL_DT for his CURRENT job title?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

Maybe you are looking for

  • Error while making GR for Subcontract PO

    Dear All Guru, While doing GR i am getting following error message "Account 41281100 requires an assignment to a CO object" i think in FI we need to maintain something so if anybody have the solution pl reply Regards, Vimlesh

  • Final Cut Crashes for apparently no reason

    Hi, I am experiencing FCP crashing for no reason, usually when i click on the timeline after, perhaps, using the source viewer. The spinning wheel starts and then never stops - i never get a 'this programme has terminated - send report' messages - ju

  • How to take iphone 3gs 32gb out of recovery

    Hi, ive just bought the above phone, it is brand new and ment to be unlocked, ive connected it to itunes and apparentley its in recovery mode, ive gone through the restore process (i realise this may re lock it) but now stuck on how to get it out of

  • Optimizing performance question

    I understand that the best practice for use of images is to resize, crop, and rotate images to the disired size and rotation before importing them into iBooks Author. Does that apply to a situation when you are re-using the same image several times i

  • Crop marks being applied incorrectly

    Hi everyone, I've just started using Illustrator CS4 and I'm trying to apply crop marks to a selection. The selection is made up of a mask, where an ellipse is making a larger shape. When I apply the crop command, it's placing the crop marks at the e