How to acheive looping in SQL

Hi Have below requirement,
a.     Take the first 7 digits of a Number string and multiply the 1st digit by 8, the 2nd digit by 7 .....etc..... the 6th digit by 3 and the 7th digit by 2;
b.     Sum up the values of the above seven multiplication;
c.     Subtract 97 from the value at b. above until you have a negative number;
d.     Digits 8 and 9 of the number, the “check digits”, will correspond with the absolute value of the negative number determined at c. above.
Example:
Passing input as number specific one, 'SK391313073'
now first 7 digits are 3913130 and perform Sum like this (3*8)+(9*7)+(1*6)+(3*5)+(1*4)+(3*3)+(0*2) [Sum wil be 121]
I have achieved till above through sql,
Now the sum I should subtract with 97 till it get equal with 8th and 9th digit (here I should loop)
in this case
121-97=24 so this is not equal to 73 (last two digits of input)
so now I need to again perform 24-97 which is -73 and abs(-73)=73 so I need to stop here,
All your help is appreciated,,

Here's a basic example of a FOR loop type structure in SQL - the pseudo column level serves as the loop variable.
You can use the WITH clause as "programming blocks" to calculate something specific and re-use the output of that in another "programming block".
The following example demonstrates the basic approach:
SQL> var n varchar2(20)
SQL> exec :n := 'SK391313073';
PL/SQL procedure successfully completed.
// parse the input string as per requirements
SQL> with number_parse as (
  2          select
  3                  level as i,
  4                  substr(:n,level,1) as ch
  5          from    dual
  6          connect by level <= length(:n)
  7  )
  8  select
  9          *
10  from       number_parse
11  /
         I CH
         1 S
         2 K
         3 3
         4 9
         5 1
         6 3
         7 1
         8 3
         9 0
        10 7
        11 3
11 rows selected.
// tad more complex: using this parsing output, determine the 1st 7 digits
SQL> with number_parse as (
  2          select
  3                  level as i,
  4                  substr(:n,level,1) as ch
  5          from    dual
  6          connect by level <= length(:n)
  7  )
  8  select i,ch from (
  9          select
10                  rownum as rno,
11                  n.*
12          from    number_parse n
13          where   ch in ('0','1','2','3','4','5','6','7','8','9')
14  )
15  where      rno between 1 and 7
16  /
         I CH
         3 3
         4 9
         5 1
         6 3
         7 1
         8 3
         9 0
7 rows selected.
// now add the calculation as required
SQL> with number_parse as (
  2          select
  3                  level as i,
  4                  substr(:n,level,1) as ch
  5          from    dual
  6          connect by level <= length(:n)
  7  ),
  8  first_7 as(
  9          select i,ch from (
10                  select
11                          rownum as rno,
12                          n.*
13                  from    number_parse n
14                  where   ch in ('0','1','2','3','4','5','6','7','8','9')
15          )
16          where   rno between 1 and 7
17          order by i desc
18  )
19  select
20          ch,
21          ch||' * '||to_char(rownum+1)    as calc,
22          to_number(ch)*(rownum+1)        as result
23  from       first_7
24  order by i
25  /
CH  CALC           RESULT
3   3 * 8              24
9   9 * 7              63
1   1 * 6               6
3   3 * 5              15
1   1 * 4               4
3   3 * 3               9
0   0 * 2               0
7 rows selected.
SQL> So SQL is capable of a FOR loop and similar type of (basic) processing that one can do in PL/SQL. However, the SQL language is not Turing Complete, and things can get messy with the above approach, in comparison with doing it in PL/SQL instead.

Similar Messages

  • I need one recurcive(unended loop) pl/sql example, its very urgent pls

    Hi,
    I need one recurcive (unended loop) pl/sql example, its very urgent pls
    Thanks,
    Sathis.

    I suppose you'll want to know how to get out of your undended loop too (although that does stop it being unended).
    Example...
    SQL> ed
    Wrote file afiedt.buf
      1  DECLARE
      2    v_cnt NUMBER := 0;
      3  BEGIN
      4    LOOP
      5      EXIT WHEN v_cnt = 1000;
      6      v_cnt := v_cnt + 1;
      7    END LOOP;
      8* END;
    SQL> /
    PL/SQL procedure successfully completed.
    SQL>

  • How to join two pl/sql tables .,.,,Urgent pls help

    Hi,
    Please tell me how to join to pl/sql tables with example
    thanks
    asp

    If your main intention is to get the common records/or getting whole records from the 2 different pl/sql arrays then , pls check this piece of code & explanation
    The SQL language has long offered the ability to apply set operations (UNION, INTERSECT, and MINUS) to the result sets of queries. In Oracle Database 10g, you can now use those same high-level, very powerful operators against nested tables (and only nested tables) in your PL/SQL programs and on nested tables declared as columns inside relational tables.
    Let's take a look at some of the syntax needed to do this, starting with UNION.
    First, I create a schema-level nested table type:
    CREATE OR REPLACE TYPE strings_nt
    IS TABLE OF VARCHAR2(100);
    Then I define a package and within it create and populate two nested tables of this type, each containing some of my father's and my favorite things:
    CREATE OR REPLACE PACKAGE favorites_pkg
    IS
    my_favorites strings_nt
    := strings_nt ('CHOCOLATE'
    , 'BRUSSEL SPROUTS'
    , 'SPIDER ROLL'
    dad_favorites strings_nt
    := strings_nt ('PICKLED HERRING
    , 'POTATOES'
    , 'PASTRAMI'
    , 'CHOCOLATE'
    PROCEDURE show_favorites (
    title_in IN VARCHAR2
    , favs_in IN strings_nt
    END;
    In this package, I also include a procedure to show the contents of a strings_nt nested table. This will come in very handy shortly.
    By defining these collections in a package, outside any program, they persist (they maintain their state and values) for the duration of my session or until I change or delete them. This means that I can now write programs outside the package to manipulate the contents of those collections.
    Note that this package has been simplified for the purposes of presenting collection functionality. In a production application, you should always take care to "hide" your package data, as with these collections, in the package body, and then provide procedures and functions to manage the data.
    Suppose, for example, that I would like to combine these two collections into a single collection of our favorites. Prior to Oracle Database 10g, I would have to write a loop that transfers the contents of one collection to another. Now, I can rely on the MULTISET UNION operator, as shown below:
    DECLARE
    our_favorites
    strings_nt := strings_nt ();
    BEGIN
    our_favorites :=
    favorites_pkg.my_favorites
    MULTISET UNION ---- Use INTERSECT , if you want to know common records
    favorites_pkg.dad_favorites;
    favorites_pkg.show_favorites (
    'ME then DAD', our_favorites);
    END;
    The output from this script is:
    ME then DAD
    1 = CHOCOLATE
    2 = BRUSSEL SPROUTS
    3 = SPIDER ROLL
    4 = PICKLED HERRING
    5 = POTATOES
    6 = PASTRAMI
    7 = CHOCOLATE
    ------------------------------

  • How could I find the SQL statement who get this message ?

    ORA-01555 caused by SQL statement below (Query Duration=11191 sec, SCN: 0x0854.723b9c32)
    ... How could I find the SQL statement who got this message ?
    Thanks, Paul

    ORA-01555 means that the UNDO/ROLLBACK space is not large enough.
    This occurs because the SELECT statement is attempting to read the UNDO, but the UNDO has been released (transactions have committed or rolled back) and reused.
    The following are SOME of the reasons I have seen this to occur:
    1) Updates in a loop, with commits happening in the same loop
    - this will mark the UNDO available quickly and quickly reuse it. Then when the SELECT wants to rebuild a block, the UNDO used to rebuild the block has been reused (solution, make the UNDO bigger)
    2) A SELECT cursor used to control a loop in which updates are performed, and a 'done' flag is marked against the current cursor record, and commits are performed at the end of each loop, prior to fetching the next record
    - same problem as above, but it hits the current process. Same solution
    3) A 'month end' activity spike occurs, and all sorts of transactions create updates. There is a report that reports the activity - amusingly it needs to start at the beginning of all the work and updates periodically by doing a huge SELECT up front. This is then used to drive a loop which attempts to get information from the various transactions that have been updated and committed. After a while, the SELECT gets an ORA-01555
    - same problem as above and same solution. Get a bigger UNDO segment.
    You say this only happens once a month. That should give a hint.
    I wouldn't bother with which SELECT statement, as much as which APPLICATIONs are being run when it happens.
    One way around this - use 10g and set the guaranteed retention period. All sorts of other things will break, by no more 1555. <g>

  • How to acheive this output during the XML conversion ?.

    I am converting the data into XML. I am using Oracle8i.
    create table emp(empno number,
    ename varchar2(20),
    deptno number);
    insert into emp values(101,'Krish',10);
    insert into emp values(102,null, 10);
    insert into emp values(103,'Scott',20);
    commit;
    CREATE OR REPLACE PROCEDURE STP_TEST_XML AS
    v_context DBMS_XMLQUERY.CTXTYPE;
    v_document CLOB;
    v_error_code VARCHAR2(3) := 'OK';
    BEGIN
    v_context:= DBMS_XMLQUERY.NEWCONTEXT('SELECT * FROM EMP');
    DBMS_XMLQUERY.USENULLATTRIBUTEINDICATOR(v_context,TRUE);
    DBMS_XMLQUERY.SETROWSETTAG(v_context,'EMPIMPORT');
    DBMS_XMLQUERY.SETROWTAG(v_context,'EMP');
    v_document := DBMS_XMLQUERY.GETXML(v_context);
    DBMS_XMLQUERY.CLOSECONTEXT(V_context);
    PRINT_XML(v_document);
    END;
    CREATE OR REPLACE PROCEDURE print_xml(result IN OUT NOCOPY CLOB) is
    xmlstr varchar2(32767);
    line varchar2(2000);
    begin
    xmlstr := dbms_lob.SUBSTR(result,32767);
    loop
    exit when xmlstr is null;
    line := substr(xmlstr,1,instr(xmlstr,chr(10))-1);
    dbms_output.put_line('| '||line);
    xmlstr := substr(xmlstr,instr(xmlstr,chr(10))+1);
    end loop;
    end;
    The output is showing as below.
    <?xml version = '1.0'?>
    <EMPIMPORT>
    <EMP num="1">
    <EMPNO>101</EMPNO>
    <ENAME>Krish</ENAME>
    <DEPTNO>10</DEPTNO>
    </EMP>
    <EMP num="2">
    <EMPNO>102</EMPNO>
    <ENAME NULL="YES"/>
    <DEPTNO>10</DEPTNO>
    </EMP>
    <EMP num="3">
    <EMPNO>103</EMPNO>
    <ENAME>Scott</ENAME>
    <DEPTNO>20</DEPTNO>
    </EMP>
    </EMPIMPORT>
    But my requirement needs my output should be as below. Please let me know how to achieve this output.
    <?xml version = '1.0'?>
    <EMPIMPORT>
    <EMP num="1">
    <EMPNO>101</EMPNO>
    <ENAME>Krish</ENAME>
    <DEPTNO>10</DEPTNO>
    </EMP>
    <EMP num="2">
    <EMPNO>102</EMPNO>
    <ENAME/>
    <DEPTNO>10</DEPTNO>
    </EMP>
    <EMP num="3">
    <EMPNO>103</EMPNO>
    <ENAME>Scott</ENAME>
    <DEPTNO>20</DEPTNO>
    </EMP>
    </EMPIMPORT>

    can you please tell me how to acheive 1,2,3  instead of the chars.
    Also if I use virtual characteristic can I able to access the query structure in the user exit like the restricted key figures etc or just the records how they appear in the cube.
    Thank you guys for the quick response.

  • How can i use one SQL statement to solve problem?

    How can i use one SQL statement to solve the question below?
    For a Table named A, there is a column named F(char type).
    Now select all the records where F like '%00' and update their F value to '%01'
    Just one SQL statement.Do not use PL/SQL block.
    How to do that?
    Thanks.

    What is the data volume for this table?
    Do you expect lots of rows to have '%00' as their value?
    Following two statements come to mind. Other experts would be able to provide better alternatives:
    If you have index on SUBSTR(f, 2):
    UPDATE A
    SET    f = SUBSTR(f,
                      1,
                      length(f) - 2) || '01'
    WHERE  substr(f,
                  -2) = '00';If most of the rows have pattern '%00':
    UPDATE A
    SET    f = SUBSTR(f,
                      1,
                      length(f) - 2) ||
               DECODE(SUBSTR(f,
                             -2),
                      '00',
                      '01',
                      SUBSTR(f,
                             -2));

  • How can I connect to SQL Server CE?

    Hi!
    How can I connect to SQL Server CE ?
    Any idea?
    I found jdbc driver for SQL Server 6.5,7.0,2000.
    But no driver for SQL CE.
    Thanks for any suggestion....

    I am also searching for same answer.
    I wanna choose Access as a db. but I can't find that so I have a no choice to select SQL2000CE though.
    I am stuck in driver problem. I can't find that.
    Should I use Oracle Lite or PointBase?
    I am under a lot of stress... like you've been...
    I wish you find and post that....

  • How do i connect to sql server 2012 from cmd .

    Hi ,
    I Installed sql server 2008 R2 and 2012 Express and sql server2014 . I can conect to sql server 2008 R2 using
    SQLCMD -L command .
    How do i connect to sql server 2012 express edition from cmd .
    Any Hep appreciated
    Thanks in advance,
    Shravan

    I HAVE ANOTHER INSTANCE NAMED TEST  WHEN I USE THE COMMAND IT GIVES ME THIS ERROR 
    HOW TO RECTIFY 
    C:\Users\HP>SQLCMD -S HP-HP/TEST
    Sqlcmd: Error: Microsoft SQL Server Native Client 11.0 : Named Pipes Provider: C
    ould not open a connection to SQL Server [67]. .
    Sqlcmd: Error: Microsoft SQL Server Native Client 11.0 : Login timeout expired.
    Sqlcmd: Error: Microsoft SQL Server Native Client 11.0 : A network-related or in
    stance-specific error has occurred while establishing a connection to SQL Server
    . Server is not found or not accessible. Check if instance name is correct and i
    f SQL Server is configured to allow remote connections. For more information see
     SQL Server Books Online..
    PLZ HELP 

  • How to compare result from sql query with data writen in html input tag?

    how to compare result
    from sql query with data
    writen in html input tag?
    I need to compare
    user and password in html form
    with all user and password in database
    how to do this?
    or put the resulr from sql query
    in array
    please help me?

    Hi dejani
    first get the user name and password enter by the user
    using
    String sUsername=request.getParameter("name of the textfield");
    String sPassword=request.getParameter("name of the textfield");
    after executeQuery() statement
    int exist=0;
    while(rs.next())
    String sUserId= rs.getString("username");
    String sPass_wd= rs.getString("password");
    if(sUserId.equals(sUsername) && sPass_wd.equals(sPassword))
    exist=1;
    if(exist==1)
    out.println("user exist");
    else
    out.println("not exist");

  • How to acheive check box in SCRIPTS

    Hi All,
    I am working on SCRIPTS, I want a check box with checked in the layout after execting. I am not changing any driver program
    How to acheive this.
    Thanks in advance

    Hi,
    You can achive check boxes in scripts using this below link
    http://abapeasy.blogspot.com/2008/03/3-easy-way-to-add-checkbox-in-your.html
    with out modifying the print program u can check the check box using the PERFORM ---ENDPERFORM CONTROL COMMAND
    see this link how to use preform contorl command in script
    http://help.sap.com/saphelp_nw04/helpdata/en/d2/cb3d07455611d189710000e8322d00/frameset.htm
    Regards
    Jagadeesh

  • How Can I Run a SQL Loader Job from Schedular

    How Can I Run a SQL Loader Job from Schedular , So that It Runs every Day.

    Depends on a couple of factors.
    If you are on a UNIX platform, you can create a shell script and schedule it with cron.
    If you are on a Windows platform, you can create a batch file and schedule it with the Windows scheduler.
    Or, if you are on Oracle 9i or 10g, you could use the external table feature instead of SQL*Loader. Then you could write a stored procedure to process the external table and schedule it using the Oracle scheduler (DBMS_JOB). This would probably be my preference.

  • How can I run a SQL script file...

    How can I run a SQL script file from a location on my computer without providing the whole path?
    Is there some way I can set a "Working folder" in SQL Plus??
    Thanks!
    Tom

    You can create an environment variable called "SQLPATH" which is a list of directories that SQL*Plus will search for your .SQL
    scripts.
    I would like to use another directory than the oracle/bin...
    How can I do this ??
    Hello,
    U can do this by this way:
    Save odm_script.sql file to the default Oracle
    directory i.e. Oracle-Home/bin and Run following command
    through SQL Plus.
    SQL>@Script_Name
    I hope this will resolve ur problem.
    Regards,
    Omer Saeed Khan.

  • How to find out the sql details of Request ID

    Hi Guru,
    I am running one crtical request i have all the SID,#serial details with me but i am not sure how i will get the sql query details of that request.so i will check why it's aking time. If any body have any script??

    Please see these docs.
    How to Find Database Session & Process Associated with a Concurrent Program Which is Currently Running. [ID 735119.1]
    bde_request.sql - Process and Session info for one Concurrent Request (11.5) [ID 187504.1]
    How to Retrieve SID Information For a Running Request [ID 280391.1]
    Thanks,
    Hussein

  • How to connect to a Sql server from Oracle using db link

    Hi All,
    Does anybody have any idea about how to connect to a sql server from oracle database using db link to syncronize the data? I need to pull the data from Sql server table to Oracle tables and relay messages back to the sql server.
    Thank you,
    Praveen.

    we have 2 products - DG4MSQL and DG4ODBC.
    DG4ODBC is for free and requires a 3rd party ODBC driver and it can connect to any 3rd party database as long as you use a suitable ODBC driver
    DG4MSQL is more powerfull as it is designed for MS SQL Server databases and it supports many functions it can directly map to SQL Server equivalents - it can also call remote procedures or participtae in distributed transactions. Please be aware DG4MSQL requires a license - it is not for free.
    Check out Metalink and you'll find notes how to configure both products.
    For a generic overview:
    Note.233876.1 Options for Connecting to Foreign Data Stores and Non-Oracle Databases
    And the setup notes:
    DG4ODBC
    Note.561033.1 How to Setup DG4ODBC on 64bit Unix OS (Linux, Solaris, AIX, HP-UX) :
    Note.466225.1 How to Setup DG4ODBC (Oracle Database Gateway for ODBC) on Windows 32bit RDBMS.HS-3-2 :
    Note.109730.1 How to setup generic connectivity (HSODBC) for 32 bit Windows (Windows NT, Windows 2000, Windows XP, Windows 2003) V817:
    Note.466228.1 How to Setup DG4ODBC on Linux x86 32bit
    DG4MSQL
    Note.466267.1 How to Setup DG4MSQL (Database Gateway for MS SQL Server) on Windows 32bit
    Note.562509.1 How to Setup DG4MSQL (Oracle Database Gateway for MS SQL Server) 64bit Unix OS (Linux, Solaris, AIX,HP-UX)
    Note.437374.1 How to Setup DG4MSQL (Oracle Database Gateway for MS SQL Server) Release 11 on Linux

  • How to install CAL 2008 SQL Server

    how to install CAL 2008 SQL Server

    Hello,
    SQL Server does not keep track of licenses. You cannot register/install licenses on a SQL Server instance. SQL Server uses
    an honor system, that means keep licensing papers of a safe place if somebody requires them later.
    Hope this helps.
    Regards,
    Alberto Morillo
    SQLCoffee.com

Maybe you are looking for

  • Asset transfer date

    Hi, Thanks for ur response, till now we were not run the depreciation from the golive date, now they were reconciling the depreciation in AW01N with manually for the last fiscal year 2007 to run the depreciation. In the asset transfer date(IMG) it is

  • Report for list of materials supplying by particular vendor

    How to find vendorwise list of materials supplying by him.

  • SUBMIT via selection screen and return gives dump

    Hi Guys, When i have used SUBMIT via SELECTION SCREEN and RETURN, it gave me the selection screen and subsequent report is executed properly without an error and when i pressed back button, it went to selection screen without any issues but the probl

  • TS3742 How to do safe boot on MacBook Pro

    How to do a safe reboot on my MacBook Pro when kernel panic message appears?

  • XI transport issue in repository.

    XI 7.0 SP10 Hi, I imported a repository object. First time,i imported this object to target system successfully. Second time,i deleted a data type in source system,then import the new version to update target system.It seems no error occured accordin