Looping a query

Hi all,
Please give me a solution to repeat a query output in a predefined number of times.
For example:
select name from test where test_id=1.
this query returns only one record but I want to print name as many times the input given by the user , if user enter five times then this query gives out put in five times
output
name
name
name
name
name
thanks
Jobin

SQL> create table test
  2  as
  3  select 'name' name, 1 test_id from dual
  4  /
Tabel is aangemaakt.
SQL> select name
  2    from test
  3       , (select level from dual connect by level <= &NUMBER_OF_TIMES)
  4   where test_id = 1
  5  /
Voer waarde voor number_of_times in: 2
oud   3:      , (select level from dual connect by level <= &NUMBER_OF_TIMES)
nieuw   3:      , (select level from dual connect by level <= 2)
NAME
name
name
2 rijen zijn geselecteerd.
SQL> select name
  2    from test
  3       , (select level from dual connect by level <= &NUMBER_OF_TIMES)
  4   where test_id = 1
  5  /
Voer waarde voor number_of_times in: 5
oud   3:      , (select level from dual connect by level <= &NUMBER_OF_TIMES)
nieuw   3:      , (select level from dual connect by level <= 5)
NAME
name
name
name
name
name
5 rijen zijn geselecteerd.Regards,
Rob.

Similar Messages

  • Looping a query with text fields

    I need to loop a query (fields: FName,LName,Phone) in
    textboxes.
    List all textboxes in one form and be able to update the db
    with all changes at once.
    <cfloop query="ListMembers">
    <input type="text" name="FName#MemberID#"
    value="#FName#">
    <input type="text" name="LName#MemberID#"
    value="#FName#">
    <input type="text" name="PhoneName#MemberID#"
    value="#FName#">
    </cfloop>
    <input type="Submit" value="Update">
    Now i need to update the db and not sure how to do that?
    Thanks for the help

    Yes. Two ways. One using Form Action and one using a form created by a form site and embedded into your web page: Embedding Forms & Encoding Email Addresses.
    OT

  • How to LOOP SELECT Query in Oracle?

    Hello
    I have a query which use a variable (:enddate) and returns a set of data. Lets assume it gives sales totals by account for a given month (specified using the variable :enddate). So the query would look something like :
    SELECT ACCOUNT_NO, SUM(SALE_AMT) TOTAL_SALES FROM SCHEMA1.SALES_LINES, :ENDDATE as END_DATE WHERE SALE_DATE BETWEEN addmonths(:ENDDATE,-1) and :ENDDATE
    GROUP BY ACCOUNT_NO
    Now, currently, I have to run this query each time I need results for a particular date, and thats OK but the problem arises when I need to run this query for an entire year. Then I have to run the query 12 times, passing the date variable each time and re-running the query.
    What I would like to do, is to create a loop which covers a time period entered by the user (e.g. user enters 12 months as the total time and 1 month as the period, and the query automatically runs for the previous 12 months, passing :enddate 1 month at a time and then presents the combined results) OR takes a bunch of dates entered in an array, (e.g. :enddate in (JAN-31-2009, Feb-28-2009, MAR-31-2009, APR-30,2009 etc) and runs the query for each of them and presents the results together in one set.
    How can I do this using a simple PLSQL loop? I would like to avoid creating a procedure if possible. Sample code will be much appreciated.
    BTW, I am using Oracle XE 10g.
    Thanks

    Hi,
    It will be more efficient to get all the results at once, rather than running 12 separate queries.
    You can do that without loops or PL/SQL, something like this:
    SELECT    account_no
    ,       TRUNC (sale_date, 'MONTH')     AS mnth
    ,        SUM (sale_amt)          AS total_sales
    FROM        schema1.sales_lines
    WHERE       sale_date     >  ADD_MONTHS (:enddate, -12)
    AND       sale_date     <= :enddate
    GROUP BY  account_no
    ,            TRUNC (sale_date, 'MONTH')
    ;Of course, you can do a query like this within PL/SQL if you need to.
    If you'd care to post some sample data (CREATE TABLE and INSERT statements) and the results you want from that data, then I could test it.
    Simplify as much as possible. For example, instead of 12 sepaarte months, you can post just 2 or 3. Adapting the solution for 12 months should be easy.
    In pure SQL, bind varibales can't be DATEs, but you could define the bind variable as a string and use TO_DATE to convert it to a DATE, OR use a substitution variable instead of a bind variable.
    The solution above works in all versions Oracle. The way you're using :enddate in the FROM clause, and a function called addmonths (rather than ADD_MONTHS) makes me wonder if you're using Oracle at all.

  • Looping over query by month

    etings,
    I have a query I am pulling that has a date field entitled, "Completed". I am attempting to loop over the query by date to slice and dice the data for a table and chart. Here is what I have done thus far...
    Setup two variables where I am only interested in the month. My plan is to fileter the date by month so I can pull the data out by month.
        <cfset startDate = #DatePart('m','01/01/09')#>
        <cfset endDate = #DatePart('m',Now())#>
    Here is my loop...
        <cfloop from = "#startDate#" to = "#endDate#" index = "i" step = "1">
    Here is one of my QoQs within the loop...
            <cfquery name="NPS0" dbtype="query">
            SELECT *
            FROM rsNPS
            WHERE #DatePart('m',rsNPS.completed)# = #i#
            </cfquery>
    I am having difficulties in getting this to work. Has anyone ever done something like this. I feel like the answer is right in front of me, but I have been staring at this code for a while. If anyone has any thoughts, I would be glad to hear them.
    ~Clay

    fs22 wrote:
             <cfquery name="NPS0" dbtype="query">
            SELECT *
            FROM rsNPS
            WHERE #DatePart('m',rsNPS.completed)# = #i#
            </cfquery>
    QoQ are a separate beast. You cannot use standard CF functions inside them.  AFAIK, QoQ only support a few functions like CAST, UPPER, LOWER, etcetera.  So as Dan suggested, you should peform the date functions in your database query.

  • Looping a query without cursor

    Hi everybody
    i want to know that is there is any way by which we can loop through Resultset of a query without using cursor for loop in plsql
    vipul

    No. Reason:
    Any SQL statement in PL/SQL is a cursor. Any rows "obtained" from a cursor, is fetched via a read-cursor-loop mechanism.
    This can be an explicit cursor, where you open the cursor and manually code the loop with the FETCH statement.
    It can be an implicit cursor, where you simply code something like [SELECT col INTO var FROM table] - in which case PL/SQL still creates a cursor and still uses a cursor fetch to read the result of that cursor.
    PL/SQL is no different than Java or Delphi or C in this aspect. It takes a SQL statement and deliver that to the SQL Engine. The SQL Engine deals with SQL statements as cursors. It returns a cursor handle to the caller. The caller then has to fetch the rows from the cursor.
    What makes PL/SQL different is that the PL/SQL language and compiler integrates so tightly with SQL, that you can mix two different programming languages in the same source code. Unlike Java, Delpi and C, you can code native SQL inside your PL/SQL code. The PL/SQL compiler is clever enough to know what it can execute, and which source lines are SQL that need to be "wrapped and delivered" to the SQL Engine.
    Question though - why do you ask for another method? What do you view as a problem with using a cursor loop to fetch rows?

  • Problem looping insert query

    I'm working on inserting a recordset up Google Calendar entries into my site database. I have a form set up that allows me to insert new entries into the data table, but when I try to loop the insert query over the Google recordset, I get nothing (no errors, but no entries added to database).
    Here's my form, which both displays the values from the Google query and populates fields (mostly hidden) with those values to submit to the Insert query. There's also a line that checks to make sure the event hasn't been canceled (canceled events are still listed, the start and end times are just set to null values):
    <form method="post" action="<cfoutput>#CurrentPage#</cfoutput>">
    <table cellpadding="2" border="1">
    <cfset thisRow = 0>
    <cfloop query="band_events">
    <cfif IsDefined("starttime") AND IsDefined("endtime") AND starttime NEQ "" AND endtime NEQ "">
    <cfset thisRow = thisRow + 1>
    <cfoutput>
    <tr>
      <td>#thisRow#</td>
      <td><input name="update#thisRow#" type="checkbox" checked="checked" /></td>
      <td><input name="calendar#thisRow#" type="hidden" value="Band" />Band</td>
      <td><input name="creator#thisRow#" type="hidden" value="#authoremail#" />#authoremail#</td>
      <td><input name="starttime#thisRow#" type="hidden" value="#starttime#" />#starttime#</td>
      <td><input name="endtime#thisRow#" type="hidden" value="#endtime#" />#endtime#</td>
      <td><input name="title#thisRow#" type="hidden" value="#title#" />#title#</td>
      <td><input name="content#thisRow#" type="hidden" value="#content#" />#content#</td>
      <td><input name="location#thisRow#" type="hidden" value="#where#" />#where#</td>
      <td><input name="ID#thisRow#" type="hidden" value="#ID#" />#ID#</td>
      <td><input name="published#thisRow#" type="hidden" value="#ISOToDateTime(published)#" />#ISOToDateTime(published)#</td>
      <td><input name="updated#thisRow#" type="hidden" value="#ISOToDateTime(updated)#" />#ISOToDateTime(updated)#</td>
    </tr>
    </cfoutput>
    </cfif>
    </cfloop>
    </table>
    <input type="hidden" name="totalRows" value="#row#" />
    <input type="submit" name="submit" value="Submit" />
    <input type="hidden" name="update_events" value="update_events" />
    </form>
    Here's the action script. There's some extra code in there to convert some of the date formats Google uses, and to account for the differences in time zones between the Google values and local time:
    <cfif StructKeyExists(form,"update_events")>
      <cfset loopCount = form["totalRows"]>
      <cfloop index="row" from="1" to="#loopCount#">
        <cfset thisCalendar = form["calendar" & row]>
        <cfset thisCreator = form["creator" & row]>
        <cfset thisStarttime = form["starttime" & row]>
        <cfset thisEndtime = form["endtime" & row]>
        <cfif TimeFormat(thisStarttime,"hh:mm tt") EQ "12:00 AM" AND TimeFormat(thisEndtime,"hh:mm tt") EQ "12:00 AM">
          <cfset thisAllDay = -1>
        <cfelse>
          <cfset thisAllDay = 0>
          <cfset thisStarttime = DateAdd("h",5,thisStarttime)>
          <cfset thisEndtime = DateAdd("h",5,thisEndtime)>
        </cfif>
        <cfset thisTitle = form["title" & row]>
        <cfset thisContent = form["content" & row]>
        <cfset thisLocation = form["location" & row]>
        <cfset thisID = form["ID" & row]>
        <cfset thisPublished = form["published" & row]>
        <cfset thisUpdated = form["updated" & row]>
        <cfquery datasource="ctband">
          INSERT INTO Events (Calendar, Created_By, All_Day, Event_Start, Event_End, Title, Content, Location, ID, Published, Updated) Values (
          <cfqueryparam value="#thisCalendar#" cfsqltype="cf_sql_varchar">,
          <cfqueryparam value="#thisCreator#" cfsqltype="cf_sql_varchar">,
          <cfqueryparam value="#thisAllDay#" cfsqltype="cf_sql_integer">,
          <cfqueryparam value="#thisStarttime#" cfsqltype="cf_sql_timestamp">,
          <cfqueryparam value="#thisEndtime#" cfsqltype="cf_sql_timestamp">,
          <cfqueryparam value="#thisTitle#" cfsqltype="cf_sql_varchar">,
          <cfqueryparam value="#thisContent#" cfsqltype="cf_sql_clob">,
          <cfqueryparam value="#thisLocation#" cfsqltype="cf_sql_varchar">,
          <cfqueryparam value="#thisID#" cfsqltype="cf_sql_varchar">,
          <cfqueryparam value="#thisPublished#" cfsqltype="cf_sql_timestamp">,
          <cfqueryparam value="#thisUpdated#" cfsqltype="cf_sql_timestamp">)
        </cfquery>
      </cfloop>
    </cfif>
    I'm thinking there must be something pretty obvious I've screwed up, but I can't for the life of me find it. Any help would be appreciated!
    JAW

    First, I see this:
    <cfset thisRow = thisRow + 1>
    Which is you counting the number of rows, I assume.  Then I see this:
    <input type="hidden" name="totalRows" value="#row#" />
    But I don't see where #row# has been set.
    You are correct. That was a combination of a couple different attempts at this and I used the wrong variable name on that line. Alas, correcting that didn't solve the problem.
    Then I see this:form["totalRows"]
    When I'm used to seeing this:
    FORM.totalRows
    I've never seen the form["name"] before.  Does that actually work?
    I read somewhere that that's a more effective way of factoring the variable in the name of the form field as an alternative to Evaluate("form.field#row#"). I think it was somewhere on Ray Camden's blog, but it was a while ago. The only reason I used it there was for consistency. That  spot could easily have been FORM.totalRows, but the others would have to be either Evaluate("FORM.calendar#row#") or form["calendar" & row]. Again, I'm learning as I go, though, so I may have used it incorrectly. It's not throwing errors though, it's just reloading a blank page, as if it's submitting the form, but not actually processing the query. That's the confusing part to me.

  • Loop in query

    Hi Guys,
    I have long query that will be loop depends on how many
    years.
    Select
    <cfloop index="i" from="#min_year#" to="#max_year#"
    step="1">
    SUM(DECODE(TO_CHAR(wbs_budget_date, 'YYYY'), #i#,
    wbs_budget_amt,NULL)) yr#i#,
    SUM(DECODE(TO_CHAR(wbs_budget_date, 'YYYY'), #i#,
    wba.Monte_Carlo_Min, NULL)) Monte_Carlo_Min#i#,
    SUM(DECODE(TO_CHAR(wbs_budget_date, 'YYYY'), #i#,
    wba.Monte_Carlo_Max, NULL)) Monte_Carlo_Max#i#,
    SUM(DECODE(TO_CHAR(wbs_budget_date, 'YYYY'), #i#,
    wba.Monte_Carlo_Likeliest, NULL)) Monte_Carlo_Likeliest#i#,
    MAX(DECODE(TO_CHAR(wbs_budget_date, 'YYYY'), #i#,
    substr(wba.Comment_Text,1,100), NULL)) Comment_Text#i#,
    MAX(DECODE(TO_CHAR(wbs_budget_date, 'YYYY'), #i#,
    wba.Monte_Carlo_Distribution_Type, NULL))
    MonteCarloDistribution#i#,
    MAX(DECODE(TO_CHAR(wbs_budget_date, 'YYYY'), #i#,
    wba.Discretionary_Spending_Status, NULL)) DiscretionarySpending#i#
    SUM(DECODE(TO_CHAR(wbs_budget_date, 'YYYY'), #i#,
    wba.MONTE_CARLO_MAX_PER, NULL)) Monte_Carlo_Max_Per#i#,
    SUM(DECODE(TO_CHAR(wbs_budget_date, 'YYYY'), #i#,
    wba.MONTE_CARLO_MIN_PER, NULL)) Monte_Carlo_Min_Per#i#,
    SUM(DECODE(TO_CHAR(wbs_budget_date, 'YYYY'), #i#,
    wba.MONTE_CARLO_LIKELIEST_PER, NULL)) Monte_Carlo_Likeliest_Per#i#
    </cfloop>
    From table name.
    This query will return an error "[Macromedia][Oracle JDBC
    Driver][Oracle]ORA-01467: sort key too long " if total year more
    then 30 years. So do anyone have any idea how to prevent this error
    happened?
    Pls give me some ideas, really appriciate ideas fron all of
    you guys.
    Regards,
    Shaffiq

    Normalize your database and you won't have problems like
    this.

  • Loop or Query?

    Database Diagram:
    http://216.128.28.125/tbar/diagram.jpg
    CFNoob - I'm trying to create a detail page but should I use
    a combination of cfquery's or loops? How can I accomplish this?
    My current code is the following attached which does not
    output the multiple updates and then those updates media files:

    Join your projects with the media, as you do your history.
    Use the GROUP attribute of the CFOUTPUT tag to organize the data.
    If you want all of the info organized by project, you'll need
    to combine all of the queries.
    Your history query seems to retrieve all of the history, not
    just the data for the project ID passed in the URL.

  • Do While loop with query?

    There seems to be no way to do a do-while loop without using
    Cfscript.
    Is there a way to place a cfquery inside cfscript?

    How so?
    The algorithm I'm trying to write is sort of recursive.
    Basically, I have a column in a table generated like so:
    Row 1: Sum of (account 1, account 2)
    Row 2: Sum of (account 3, account 4)
    Row 3: sum of rows 1-2
    Row 4: Sum of (account 5, account 6)
    Row 5: Sum of rows 3-4
    So basically, I'm trying to query for all of the accounts
    that make up row 5 (which in this case is ALL of the accounts). It
    looks like I'm going to have to work backwards from the starting
    row (5) and keep checking the rows that its composed of until I hit
    some base case (no more summation rows?)

  • Loop a query and set variables for each record

    Hi
    I have a query - produces two records: such as below for
    columns Addon & Status
    Incidents 1
    TimeManagement 1
    I would like to loop through these to produce two session
    variables
    Session.Incidents and Session.TimeManagement with Status
    being the value
    I could fix these but possibly there will be more recrods
    returned in the future and I'd like to make it dynamic.
    Really appreciate any help.
    Simon

    <cfoutput query="myQuery">
    <cfset "Session.#addon#" = #Status#>
    </cfoutput>

  • Loop through Query String in ASP

    Hi,
    I am new to ASP and am trying to loop through values in a
    query string
    separated by a comma, for example:
    /site/search/results.asp?ids=19736a,20248a,14952a,19956a
    I need to construct SQL from this something like
    SELECT * FROM MyTable WHERE
    ID = 19736a OR
    ID = 20248a OR
    ID = 14952a OR
    ID = 19956a
    I am just unsure on how to separate all the values from the
    query string.
    Thanks for your advice.

    Oh, in the example below there is no space between the id
    numbers in the
    querystring.
    eg. ids=1,23,456,2
    If you do have spaces then you need to adjust the split
    accordingly
    eg. ids=1, 23, 456, 2
    you would use myIdArray=split(idStr,", ")
    note the space after the comma.
    just make sure you always use the same format in your
    querystring
    Justin
    "Justin Reid" <[email protected]>
    wrote in message
    news:e6osem$dfj$[email protected]..
    > You need to create an array of ids and then add them to
    your SQL.
    > Something like:
    > <%
    > If Request.QueryString("ids") <> "" Then
    > Dim idStr, cnt, varID
    > 'get the string of id'
    > idStr = Request.QueryString("ids")
    > 'create the array
    > myIdArray=split(idStr,",")
    > cnt=0
    > 'loop though the array and add to a new string
    > for i=o to ubound(myIdArray)
    > If cnt > 0 Then varID = (varID & " OR")
    > varID = (varID & " id = " & cStr(myIdArray(i)))
    > cnt=cnt+1
    > next
    > End If
    > %>
    >
    > Then simply add you new SQL segment to your recordset.
    > Something like
    >
    > SELECT * FROM MyTable WHERE" + Replace(varID, "'", "''")
    + "
    >
    > Hope that helps
    >
    > Justin
    >
    > "Shaun" <[email protected]> wrote in
    message
    > news:e6ole1$56v$[email protected]..
    >> Hi,
    >>
    >> I am new to ASP and am trying to loop through values
    in a query string
    >> separated by a comma, for example:
    >>
    >>
    /site/search/results.asp?ids=19736a,20248a,14952a,19956a
    >>
    >> I need to construct SQL from this something like
    >>
    >> SELECT * FROM MyTable WHERE
    >> (
    >> ID = 19736a OR
    >> ID = 20248a OR
    >> ID = 14952a OR
    >> ID = 19956a
    >> )
    >>
    >> I am just unsure on how to separate all the values
    from the query string.
    >>
    >> Thanks for your advice.
    >>
    >
    >

  • How to automate/parameterize/loop power query?

    Is it possible to write a single generic powerquery command that'll loop through a list of URLs and load the data to a single table? the webpages in question have the same format & table names, just the data contained within is different. I verified
    this by manually defining a powerquery from web import, importing, changing the url, and hitting refresh
    Is it possible to write a generic powerquery import to pull the data in and have it loop to append the data to a target worksheet?
    I tried macro recording some of the powerquery actions of defining an import but it didn't record anything so im assuming i cant use a vba loop to do this.
    I want to avoid having to manually define each from web import explicitly. There's a few hundred i'd need to do.
    Jakub @ Adelaide, Australia

    Here's a quick walkthrough for how to do something like this. I recommend reading through to the end before trying this, because there will a step later on which you'll actually want to do first to simplify things.
    Let's say I want to get presidential election results for multiple US States from Wikipedia. So to start, I use the "From Web" option inside Power Query and specify an URL of
    http://en.wikipedia.org/wiki/California. This lets me pick between several sections of the web page, and I choose the one called "Presidential elections results" and edit it. The results look good
    in the preview, so I go to the "advanced editing" view that shows me the M query:
    let
        Source = Web.Page(Web.Contents("http://en.wikipedia.org/wiki/California")),
        Data5 = Source{5}[Data],
        ChangedType = Table.TransformColumnTypes(Data5,{{"Year", type number}, {"Republican", type text}, {"Democratic", type text}})
    in
        ChangedType
    The numeric index "5" worries me a little because I suspect that there's not enough regularity in the Wikipedia pages for the US states for the 6th section to always be the one that I want. So I edit the query to index by the section name instead
    and confirm that it still produces the results I want:
    let
        Source = Web.Page(Web.Contents("http://en.wikipedia.org/wiki/California")),
        Data5 = Source{[Caption="Presidential elections results"]}[Data],
        ChangedType = Table.TransformColumnTypes(Data5,{{"Year", type number}, {"Republican", type text}, {"Democratic", type text}})
    in
        ChangedType
    Now I need to turn this into a function that can be applied to multiple pages. The only way to do that is to edit the M query directly, but the transformation is relatively straightforward. Again, I confirm that the output is still what I expected after
    making these changes.
    let
        Election.Results = (state) => let
            Source = Web.Page(Web.Contents("http://en.wikipedia.org/wiki/" & state)),
            Data5 = Source{[Caption="Presidential elections results"]}[Data],
            ChangedType = Table.TransformColumnTypes(Data5,{{"Year", type number}, {"Republican", type text}, {"Democratic", type text}})
        in
            ChangedType
    in
        Election.Results("California")
    Now, I want to apply this function to multiple web pages. These might come from a different Excel sheet or from an external file, but I'm just going to build a table of web pages manually. I'll keep the function around, but won't use it just yet in the overall
    formula. Once more, I confirm that the output is what I expect, which is a single table listing three states.
    let
        Election.Results = (state) => let
            Source = Web.Page(Web.Contents("http://en.wikipedia.org/wiki/" & state)),
            Data5 = Source{[Caption="Presidential elections results"]}[Data],
            ChangedType = Table.TransformColumnTypes(Data5,{{"Year", type number}, {"Republican", type text}, {"Democratic", type text}})
        in
            ChangedType,
        States = Table.FromRows({{"California"}, {"Idaho"}, {"Massachusetts"}}, {"State"})
    in
        States
    Now I can use the "Insert Custom Column" feature of the UI to apply my function to the State column. This looks like "=Election.Results([State])" in the dialog. But when I click OK, something unpleasant happens: I get prompted several
    times for "data privacy" settings for each of the URLs I'm trying to access. This is quite annoying, and we're looking for ways to improve the experience -- perhaps by letting you pick that the privacy settings apply to all of
    http://en.wikipedia.org and not just to the specific URL you're trying to access.
    Meanwhile, you can achieve the same thing manually with a kind of underhanded trick by creating a throwaway query which references
    http://en.wikipedia.org and one other website, and using the "data privacy" prompt from that query to define a privacy rule for the entire domain. Exit the editor and create a new "Blank Query" with
    this single formula: "= Binary.Length(Web.Contents("http://en.wikipedia.org")) + Binary.Length(Web.Contents("http://www.bing.com"))" This will prompt
    you to pick a privacy setting for those two websites (I would suggest that "Public" is the right choice). Once you've done that, you can discard this query; its work is done.
    Now if you go back and repeat the steps for the "elections" query, you'll avoid the privacy prompt.
    At this point, you'll have a table with two columns: one that has the state, and one that has the results as Table values. We want to expand out those values, so we click on the expansion indicator in the column header for Custom and pick all fields. The
    result is a table with four columns: State, Custom.Year, Custom.Republican and Custom.Democratic. The latter three fields can be renamed from either the UI or by editing the M code. In my case, I ended up with a program which looks like this:
    let
        Election.Results = (state) => let
            Source = Web.Page(Web.Contents("http://en.wikipedia.org/wiki/" & state)),
            Data5 = Source{[Caption="Presidential elections results"]}[Data],
            ChangedType = Table.TransformColumnTypes(Data5,{{"Year", type number}, {"Republican", type text}, {"Democratic", type text}})
        in
            ChangedType,
        States = Table.FromRows({{"California"}, {"Idaho"}, {"Massachusetts"}}, {"State"}),
        InsertedCustom = Table.AddColumn(States, "Custom", each Election.Results([State])),
        #"Expand Custom" = Table.ExpandTableColumn(InsertedCustom, "Custom", {"Year", "Republican", "Democratic"}, {"Year", "Republican", "Democratic"})
    in
        #"Expand Custom"
    And the job is done!
    Actually, the hard part might just be getting started. Finding a set of web sites which is consistent enough for a single parsing function to work can be rare. As an example, when I tried to add "Washington_(U.S._state)" to my list of states, I
    discovered that its table was formatted differently than the others. And when I tried to add "New_york_state" to the list of states, I found that its section was named "New York State Presidential Election Results" instead of just "Presidential
    election results". So it's possible that you'll have to do an awful lot of tweaking.
    Nonetheless, this should cover the basic steps and help you get started.

  • While loop in query is going under infinite loop

    Declare
    @StartDate_in date,
    @EndDate date
    Set @StartDate_in = cast('2000-01-01' as date)
    Set @EndDate = cast('2010-12-31' as date)
    declare @month int
    declare @year int
    declare @endyear int
    declare @startdate date
    set @startdate= @startdate_in
    set @month = month(@StartDate_in)
    set @year= year(@StartDate_in)
    set @endyear= year(@EndDate)
    while @year<=@endyear
    Begin
    while month(@startdate)<=12 and @year<=@endyear
    begin
    print (@year);
    print (month(@startdate));
    INSERT Into target
    ( YEAR,
    MONTH,
    MONTH_VAL,
    L_DT,
    U_DT,
    S_DT,
    E_DT
    Values
    ( datepart(yyyy,@StartDate) ,
    datepart(month,@StartDate) ,
    substring(datename(month,@StartDate),1,3),
    GETDATE(),
    GETDATE(),
    (GETDATE()-1),
    null
    set @StartDate = dateadd(month,1,@StartDate);
    set @month=1;
    end
    set @year=@year+1;
    print (@year);
    print (@month);
    end
    The query although with exit condtion given in the while loop is not ending and executing infinetly
    ddl of target
    CREATE TABLE target(
    [TIME_ID] [int] IDENTITY(1,1) NOT NULL,
    [START_DT] [date] NULL,
    [E_DT] [date] NULL,
    [L_DT] [datetime] NULL,
    [U_DT] [datetime] NULL,
    [YEAR] varchar (5) NULL,
    [MONTH] varchar(5) NULL,
    [MONTH_VAL] [varchar](5) NULL
    ) ON [PRIMARY]
    GO
    Mudassar

    Try followings:Declare
    @StartDate_in date,
    @EndDate date
    Set @StartDate_in = cast('2000-01-01' as date)
    Set @EndDate = cast('2010-12-31' as date)
    declare @month int
    declare @year int
    declare @endyear int
    declare @startdate date
    declare @innerloopyear int
    set @startdate= @startdate_in
    set @month = month(@StartDate_in)
    set @year= year(@StartDate_in)
    set @endyear= year(@EndDate)
    set @innerloopyear = @year
    while @year<=@endyear
    Begin
    while month(@startdate)<=12 and @year>=@innerloopyear
    begin
    print (@year);
    print (month(@startdate));
    INSERT Into target
    ( YEAR,
    MONTH,
    MONTH_VAL,
    L_DT,
    U_DT,
    S_DT,
    E_DT
    Values
    ( datepart(yyyy,@StartDate) ,
    datepart(month,@StartDate) ,
    substring(datename(month,@StartDate),1,3),
    GETDATE(),
    GETDATE(),
    (GETDATE()-1),
    null
    set @StartDate = dateadd(month,1,@StartDate);
    set @innerloopyear = YEAR(@startdate)
    set @month=1;
    end
    print 'hello'
    set @year=@year+1;
    --set @StartDate = DATEADD(year,1,@StartDate)set @innerloopyear = @year
    print (@year);
    print (@month);
    end
    I have formatted change in "Bold".

  • How to loop sql query

    hi ,
    i've already define date value as below ,
    DEFINE START_TIME = 2011-08-12 09:00:00
    DEFINE END_TIME = 2011-08-12 10:00:00And Quering the table depending on the Defined date as below ,
    select * from My_Table
    where
    ( to_date(Accounting_Start_Time,'yyyy-mm-dd HH24:MI:SS') >= to_date('&start_time','yyyy-mm-dd HH24:MI:SS') and to_date(Accounting_Stop_Time,'yyyy-mm-dd HH24:MI:SS') <= to_date('&end_time','yyyy-mm-dd HH24:MI:SS')
    OR to_date(Accounting_Start_Time,'yyyy-mm-dd HH24:MI:SS') >= to_date('&start_time','yyyy-mm-dd HH24:MI:SS') and to_date(Accounting_Stop_Time,'yyyy-mm-dd HH24:MI:SS') >=to_date('&end_time','yyyy-mm-dd HH24:MI:SS') and to_date(Accounting_Start_Time,'yyyy-mm-dd HH24:MI:SS') <= to_date('&end_time','yyyy-mm-dd HH24:MI:SS')
    OR to_date(Accounting_Start_Time,'yyyy-mm-dd HH24:MI:SS') <= to_date('&start_time','yyyy-mm-dd HH24:MI:SS') and to_date(Accounting_Stop_Time,'yyyy-mm-dd HH24:MI:SS') <= to_date('&end_time','yyyy-mm-dd HH24:MI:SS') and to_date(Accounting_Stop_Time,'yyyy-mm-dd HH24:MI:SS') >= to_date('&start_time','yyyy-mm-dd HH24:MI:SS')
    OR to_date(Accounting_Start_Time,'yyyy-mm-dd HH24:MI:SS') <= to_date('&start_time','yyyy-mm-dd HH24:MI:SS') and to_date(Accounting_Stop_Time,'yyyy-mm-dd HH24:MI:SS') >= to_date('&end_time','yyyy-mm-dd HH24:MI:SS'));but now i want to query the table on hour basis ,
    Any help please ,

    Hi,
    Sorry, it's still not clear what you want.
    I see the INSERT statements now, but not the CREATE TABLE statement, anything about your Oracle version, or, most imporatantly, the results you're trying to produce.
    Post the exact results you want from that sample data. Format the output, so it's easy to read. Whenever you post formatted text (such as query results) on this site, type these 6 characters:
    \(small letters only, inside curly brackets) before and after each section of formatted text, to preserve spacing.
    Do you still want to pass start_time and end_time parameters to the query (and have it repeat something fro every hour between those points)?  If so, give a couple of sets of parameters and the results you want from the same sample data for each set.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Nested If loop on Query

    Hi All,
    Need some help on one of the query I have. I have several conditions to be fullfilled and I need to use if-then-else syntax. However, izzit possible to if -then-else syntax on SAP B1 Query ? I have tried a few times and it returns me with various error. So far only when syntax works for me.
    Thank You
    Best regards,
    Alex

    Hi Thanga,
    I have tried it out, but it doesn't work. I think there are something wrong wtih the syntax but I cant find the error.
    SELECT DISTINCT T0.DocNum as 'DO#' , T0.DocStatus as 'Status', (Datename (mm, T0.CreateDate)) + (Datename (yyyy, T0.CreateDate)) as '@MonthYear',   T0.CreateDate, T0.DocTime,
    T0.CardName, T1.ItemCode, round((T1.Quantity),2), T1.WhsCode, T1.U_Closing_Date, T1.U_Closing_Time2, DATEDIFF(dd, T0.[CreateDate], T1.U_Closing_Date) as "Day Difference",
    If (T0.DocTime > '999' AND T1.U_Closing_Time2 > '999') BEGIN (((LEFT ((T0.DocTime),2)*60) + (RIGHT ((T0.DocTime),2))) - ((LEFT ((T1.U_Closing_Time2),2)*60) + (RIGHT ((T1.U_Closing_Time2),2)))) END ELSE
    If (T0.DocTime < '999' AND T1.U_Closing_Time2 > '999') BEGIN (((LEFT ((T0.DocTime),1)*60) + (RIGHT ((T0.DocTime),2))) - ((LEFT ((T1.U_Closing_Time2),2)*60) + (RIGHT ((T1.U_Closing_Time2),2)))) END ELSE
    If (T0.DocTime > '999' AND T1.U_Closing_Time2 < '999') BEGIN (((LEFT ((T0.DocTime),2)*60) + (RIGHT ((T0.DocTime),2))) - ((LEFT ((T1.U_Closing_Time2),1)*60) + (RIGHT ((T1.U_Closing_Time2),2)))) END ELSE
    If (T0.DocTime < '999' AND T1.U_Closing_Time2 < '999') BEGIN (((LEFT ((T0.DocTime),1)*60) + (RIGHT ((T0.DocTime),2))) - ((LEFT ((T1.U_Closing_Time2),1)*60) + (RIGHT ((T1.U_Closing_Time2),2)))) END
    FROM ODLN T0 INNER JOIN DLN1 T1 ON T0.DocEntry = T1.DocEntry
    WHERE DATEDIFF(dd, T0.[CreateDate], T1.U_Closing_Date) < '0' AND T1.WhsCode = [%0]

Maybe you are looking for