Algorithm in PL/SQL

I have a table which contains versions of a tool installed in the format
1.0.2
1.0.3
1.0.3.1
1.0.4
1.0.4.1
1.0.4.2
I want a numeric equivalent of these versions , 1.0.3.1 is a sub version of 1.0.3
The numeric equivalent should follow the below rule
i.e. numeric(1.0.3)<numeric(1.0.3.1)<numeric(1.0.4).
This has to be done using PL/SQL , there should be an algorithm for it
Not necessarily to provide the exact code , pseudo code / logic is also welcome
I am on 11g

Raunaq wrote:
Just one condition more , that versions can be alphanumeric also
like 1.0.2a.3
it will not be like like 1.0.2ab.3---there will be just one character
And you didn't think that that small bit of additional requirement was important to mention at the start?
If you're going to consider alpha characters in it, then you need something that determines that sub versions without an alpha come before (or after if you like the choice is yours) the ones with alphas.
So, let's assume that those without alphas come before the ones with alphas, we not have to look at the ascii values of the characters.  You're indicating that the alphas will be just something like a-z, so if we assume the non alpha sub versions have a space character, we know that a space is ascii 32 and will come before the alphas...
SQL> ed
Wrote file afiedt.buf
  1  with t as (select '1.0.2' as ver from dual union all
  2             select '1.0.3' from dual union all
  3             select '1.0.3.1' from dual union all
  4             select '1.0.3a.1' from dual union all
  5             select '1.0.3.2' from dual union all
  6             select '1.0.4' from dual union all
  7             select '1.0.4.1' from dual union all
  8             select '1.0.4.2' from dual
  9            )
10  --
11  -- end of test data
12  --
13  select ver
14        ,nvl(regexp_substr(ver2,'[^.]+',1,1),'000 ')||
15         nvl(regexp_substr(ver2,'[^.]+',1,2),'000 ')||
16         nvl(regexp_substr(ver2,'[^.]+',1,3),'000 ')||
17         nvl(regexp_substr(ver2,'[^.]+',1,4),'000 ') as order_value
18  from   (select ver, regexp_replace('00'||regexp_replace(ver||' ','([0-9])\.','\1 .'),'(\.)','\100') as ver2 from t)
19* order by 2
SQL> /
VER      ORDER_VALUE
1.0.2    001 000 002 000
1.0.3    001 000 003 000
1.0.3.1  001 000 003 001
1.0.3.2  001 000 003 002
1.0.3a.1 001 000 003a001
1.0.4    001 000 004 000
1.0.4.1  001 000 004 001
1.0.4.2  001 000 004 002
8 rows selected.
So, now the ordering of the data is done based on strings rather than numeric values.
Whilst that does allow you to compare versions using versionA < versionB or versionA > versionB, I personally consider it bad practice to compare strings using numeric range operators... even if it does work.
In that case I'd probably go for a version that includes the alphas based on their ascii values as part of the overall numeric value... something like...
SQL> ed
Wrote file afiedt.buf
  1  with t as (select '1.0.2' as ver from dual union all
  2             select '1.0.3' from dual union all
  3             select '1.0.3.1' from dual union all
  4             select '1.0.3a.1' from dual union all
  5             select '1.0.3.2' from dual union all
  6             select '1.0.4' from dual union all
  7             select '1.0.4.1' from dual union all
  8             select '1.0.4.2' from dual
  9            )
10  --
11  -- end of test data
12  --
13  select ver
14        ,(ascii(upper(p4_a))-32)+
15         p4_n*100+
16         (ascii(upper(p3_a))-32)*10000+
17         p3_n*1000000+
18         (ascii(upper(p2_a))-32)*100000000+
19         p2_n*10000000000+
20         (ascii(upper(p1_a))-32)*1000000000000+
21         p1_n*100000000000000 as num_value
22  from   (select ver
23                ,nvl(regexp_substr(regexp_substr(ver,'[^.]+',1,1),'[0-9]+'),'0') as p1_n
24                ,nvl(regexp_substr(regexp_substr(ver,'[^.]+',1,1),'[a-z ]+'),' ') as p1_a
25                ,nvl(regexp_substr(regexp_substr(ver,'[^.]+',1,2),'[0-9]+'),'0') as p2_n
26                ,nvl(regexp_substr(regexp_substr(ver,'[^.]+',1,2),'[a-z ]+'),' ') as p2_a
27                ,nvl(regexp_substr(regexp_substr(ver,'[^.]+',1,3),'[0-9]+'),'0') as p3_n
28                ,nvl(regexp_substr(regexp_substr(ver,'[^.]+',1,3),'[a-z ]+'),' ') as p3_a
29                ,nvl(regexp_substr(regexp_substr(ver,'[^.]+',1,4),'[0-9]+'),'0') as p4_n
30                ,nvl(regexp_substr(regexp_substr(ver,'[^.]+',1,4),'[a-z ]+'),' ') as p4_a
31          from   t)
32* order by 2
SQL> /
VER                          NUM_VALUE
1.0.2                  100000002000000
1.0.3                  100000003000000
1.0.3.1                100000003000100
1.0.3.2                100000003000200
1.0.3a.1               100000003330100
1.0.4                  100000004000000
1.0.4.1                100000004000100
1.0.4.2                100000004000200
8 rows selected.
This is allowing 0-99 for the numeric part of each sub version as well as 0-99 for the ascii value of the alpha character (I've subtracted 32 in my code just to make non-alpha subversions have a value of 0 for the alpha part, and using UPPER isn't really necessary as I'm subtracting 32, but just brings the ascii values down to a lower level so there's less danger of having an ascii value over 99.

Similar Messages

  • Encryption algorithms used in SQL Compact Edition 3.5

    Hi,
    In the info for SQL Compact Edition 3.5 it states that one of the features is:
    Support for newer and more secure encryption algorithms.
    I can't seem to find details of exactly what these new, more secure algorithms are. It appears 3.1 used 128-bit RSA. Is this the same in 3.5, or has this changed?
    Thanks

    The official word is now out here: http://209.34.241.67/laxmi/archive/2008/04/15/sql-server-compact-database-file-security.aspx

  • Data Structures in SQL Server

    Friends,
    I am giving a session on "Data structures and SQL Server" for one of the SQL Server communities in India.
    My idea is to explain high level concepts of data structures (Stacks, Queues, Linked lists, Trees, Graphs etc.)
    here are my questions.
    Like to know how data structure concepts are implemented SQL Server components (in a high level).
    Here are some hints in my mind:
    1. Queues - SQL Server - DMVs for Processor Queue length, Disk Queue length etc.
    2. Linked Lists - SQL Server - Previous and Next page pointers in Page headers (and DBCC IND)
    3. Trees - SQL Server - Btrees in Indexes (DBCC IND and DBCC PAGE of Index pages)
    3. Linear Search - SQL Server - Table Scan
    4. Binary Search - SQL Server - Index Seek
    What i need is:
    1. Sorting algorithm used in SQL Server?
    2. Stack concept used in SQL Server? I think No
    3. what else data structure concepts are implemented in SQL Server (that can be demonstrated)
    Note: level: 300 - Intermediate to Advanced.
    Thanks in advance
    Ramkumar
    [email protected]
    Ramkumar Gopal Living For SQL Server Blog: http://www.sqlservercentral.com/blogs/livingforsqlserver/ Facebook: https://www.facebook.com/#!/groups/livingforsqlserver/ Twitter: https://twitter.com/LivingForSQL

    Hello,
    Take a look at some structures created for In-Memory OLTP (hash indexes, etc.)
    http://download.microsoft.com/download/5/F/8/5F8D223F-E08B-41CC-8CE5-95B79908A872/SQL_Server_2014_In-Memory_OLTP_TDM_White_Paper.pdf
    BUF Structures.
    http://blogs.msdn.com/b/karthick_pk/archive/2013/03/16/sql-server-memory.aspx
    Hope this helps.
    Regards,
    Alberto Morillo
    SQLCoffee.com

  • Data Type and Algorithm

    I require some help with the line intersection algorithm in PL SQl
    I have worked with it on C programs, but not to sure how to create type and variables in PL SQL
    I have written the code for the algorithm, i require help to create the data types and testing the algorithm.
    I not too sure if my declares variables which will be data type number are correct
    ( x1, y1, x2, y2, x3, y3, x4, y4,xc, yc;
    --a1, a2, b1, b2, c1, c2; /* Coefficients of line eqns. */
    -- lr1, r2, r3, r4; /* 'Sign' values */
    -- denom, num; /* Intermediate values */
    -- Bsign and Asign will have to be type boolean
    Create or Replace type Intersect_point object
    ( x1 number, x2 number, y1 number, y2 number, x3 number, y3 number, x4 number, y4 number, xc number, yc number,
    a1 number, a2 number, b1 number, b2 number, c1 number, c2 number, r1 number, r2 number, r3 number, r4 number,
    demon number, num number,
    Bsign boolean, Asign boolean)
    create or replace type body box as
    a1:=y2-y1;
    b1:=x1-x2;
    c1:=x2*y1-x1*y2;
    r3:= a1*x3+b1*y3+c1;
    r4:= a1*x4+b1*y4+c1;
    asign:=r3<0;
    bsign:=r4<0;
    if ( (r3!=0) and (r4!=0) and (asign = bsign) ) then
    return 'False';
    -- /* Check signs of r3 and r4. If both point 3 and point 4 lie on
    -- * same side of line 1, the line segments do not intersect.
    else
    a2:= y4-y3;
    b2:= x3-x4;
    c2:= x4*y3-x3*y4;
    r1:=a2*x1+b2*y1+c2;
    r2:=a2*x2+b2*y2+c2;
    asign:=r1<0;
    bsign:=r2<0;
    if (r1 != 0) and (r2 != 0) and (asign =bsign) then
    return 'False';
    /* Check signs of r1 and r2. If both point 1 and point 2 lie
    * on same side of second line segment, the line segments do
    * not intersect.
    else
    denom :=a1*b2-a2*b1;
    if(denom=0) then
    return 'NULL';
    --they are collinear
    else
    num:=b1*c2-b2*c1;
    xc:= num/denom;
    xc:=a2*c1-a1*c2;
    yc:= num/denom;
    return 'True';
    ---- This shows they intersect. HOW can i code to get output for
    --intersection points xc yx?
    end if;
    end if;
    end if;

    Hi
    Can you tell me the your requirement (i.e) incoming receipts and outgoing payments will be cleared (i.e on what basis).
    Thanks
    balu

  • Using dbms_lob to load image into table

    I am trying to load a set of images from my DB drive into a table. This works fine when I try to load only 1 record. If I try to load more than 1 record, first gets created but I get this error, and it doesn't load the images for the rest of them.
    ORA-22297:     warning: Open LOBs exist at transaction commit time
    Cause:     An attempt was made to commit a transaction with open LOBs at transaction commit time.
    Action:     This is just a warning. The transaction was commited successfully, but any domain or functional indexes on the open LOBs were not updated. You may want to rebuild those indexes.
    Am I missing something in the code that's needed?
    in_file UTL_FILE.FILE_TYPE;
    bf bfile;
    b blob;
    src_offset integer := 1;
    dest_offset integer := 1;
    CURSOR get_pics is select id from emp;
    BEGIN
    FOR x in get_pics LOOP
    BEGIN
    insert into stu_pic(id,student_picture)
    values(x.id,empty_blob()) returning student_picture into b;
    l_picture_uploaded := 'Y';
    bf := bfilename('INTERFACES',x.student_id || '.' || p_image_type);
    dbms_lob.fileopen(bf,dbms_lob.file_readonly);
    dbms_lob.open(b,dbms_lob.lob_readwrite);
    dbms_lob.loadBlobFromFile(b,bf,dbms_lob.lobmaxsize,dest_offset,src_offset);
    dbms_lob.close(b);
    dbms_lob.fileclose(bf);
    EXCEPTION when dup_val_on_index then null;
    END;
    END LOOP;
    END;

    There are two methods you can use.
    1. Create an external table with those images(BLOB column) and then use that external table to insert into another table.
    Demo as follows:
    This is my pdf files
    C:\Saubhik\Assembly\Books\Algorithm>dir *.pdf
    Volume in drive C has no label.
    Volume Serial Number is 6806-ABBD
    Directory of C:\Saubhik\Assembly\Books\Algorithm
    08/16/2009  02:11 PM         1,208,247 algorithms.pdf
    08/17/2009  01:05 PM        13,119,033 fci4all.com.Introduction_to_the
    d_Analysis_of_Algorithms.pdf
    09/04/2009  06:58 PM        30,375,002 sedgewick-algorithms.pdf
                   3 File(s)     44,702,282 bytes
                   0 Dir(s)   7,474,593,792 bytes free
    C:\Saubhik\Assembly\Books\Algorithm>This is my file with which I'll load the pdf files as BLOB
    C:\Saubhik\Assembly\Books\Algorithm>type mypdfs.txt
    Algorithms.pdf,algorithms.pdf
    Sedgewick-Algorithms.pdf,sedgewick-algorithms.pdf
    C:\Saubhik\Assembly\Books\Algorithm>Now the actual code
    SQL> /* This is my directory object */
    SQL> CREATE or REPLACE DIRECTORY saubhik AS 'C:\Saubhik\Assembly\Books\Algorithm';
    Directory created.
    SQL> /* Now my external table */
    SQL> /* This table contains two columns. 1.pdfname contains the name of the file
    DOC>   and 2.pdfFile is a BLOB column contains the actual pdf*/ 
    SQL> CREATE TABLE mypdf_external (pdfname VARCHAR2(50),pdfFile BLOB)
      2         ORGANIZATION EXTERNAL (
      3           TYPE ORACLE_LOADER
      4            DEFAULT DIRECTORY saubhik
      5            ACCESS PARAMETERS (
      6              RECORDS DELIMITED BY NEWLINE
      7              BADFILE saubhik:'lob_tab_%a_%p.bad'
      8              LOGFILE saubhik:'lob_tab_%a_%p.log'
      9              FIELDS TERMINATED BY ','
    10              MISSING FIELD VALUES ARE NULL
    11               (pdfname char(100),blob_file_name CHAR(100))
    12              COLUMN TRANSFORMS (pdfFile FROM lobfile(blob_file_name) FROM (saubhik) BLOB)
    13            )
    14            LOCATION('mypdfs.txt')
    15         )
    16         REJECT LIMIT UNLIMITED;
    Table created.
    SQL> SELECT pdfname,DBMS_LOB.getlength(pdfFile) pdfFileLength
      2  FROM   mypdf_external;
    PDFNAME                                            PDFFILELENGTH
    Algorithms.pdf                                           1208247
    Sedgewick-Algorithms.pdf                                30375002
    SQL> Now, you can use this table for any operation very easily. Even for your loading into another table!.
    2. Use of DBMS_LOB like this
    /* Loading a image Winter.jpg in the BLOB column as BLOB!*/
    DECLARE
      v_src_blob_locator BFILE := BFILENAME('SAUBHIK', 'Winter.jpg');
      v_amount_to_load   INTEGER := 4000;
      dest_lob_loc BLOB;
    BEGIN
      --Insert a empty row with id 1
      INSERT INTO test_my_blob_clob VALUES(1,EMPTY_BLOB(),EMPTY_CLOB())
       RETURNING BLOB_COL INTO dest_lob_loc;
      DBMS_LOB.open(v_src_blob_locator, DBMS_LOB.lob_readonly);
      v_amount_to_load := DBMS_LOB.getlength(v_src_blob_locator);
      DBMS_LOB.loadfromfile(dest_lob_loc, v_src_blob_locator, v_amount_to_load);
      DBMS_LOB.close(v_src_blob_locator);
      COMMIT;
    --id=1 is created with Winter.jpg populated in BLOB_COL and CLOB_COL is empty.  
    END;Now user this code to create a procedure with parameter and use that in loop.

  • Forms md5

    Hello.
    I've been looking for some way to encrypt the passwords for database users. What I want is prevent them from logging on directly to the database with their username and password, so the password is encrypted before logging on to the database.
    I'm curious how I could run a hashing function like md5 in forms (I'm not logged in to the database so I can't use dbms_obsfucation). I could only find one project for md5 in pl/sql but was discontinued because of the above mentioned package. Will I have to code the algorithm in pl/sql?

    Well, you don't pass the component to the method. (The error message already told you that.) You need a String. (Your code tells you that.)
    So how do you get a String from a JPasswordField? Well unfortunately that's a little more difficult that most text fields. Usually you do the obvious thing and call the getText() method, but in this case it's deprecated and you are supposed to use the getPassword() method. But it returns an array of chars.
    Left as an exercise for the student to find out how to make an array of chars into a String.

  • Bin Packing algorithum

    Hello Friends,
    Please help me out ..
    I want to generate the code like bin packing algorithm in pl sql ..
    So is there any utility or algorithm exits in oracle that is similar to bin packaging algorithm...
    Thanks

    As Hoek mentioned, there is no built in utility for bin packing in Oracle, because there is no generic rule for it.  All it depends upon different business rule and approaches.  If you write the question in PL/SQL forum by providing Oracle Version, Create Table and insert statement, Logic behind required output in simple English language; then I am sure you can also get the answer as I https://forums.oracle.com/thread/2612134
    Regards
    Girish Sharma

  • Skyline Query Challenge

    Suppose you are shopping for a new car, and are specifically looking for a big
    car with decent gas mileage. Unfortunately, we are trying to satisfy the two
    conflicting goals. If we are querying the Cars relation in the database, then we
    certainly can ignore all models that are worse than others by both criteria. The
    remaining set of cars is called the Skyline.
    More formally the Skyline is defined as those points which are not dominated by
    any other point. A point dominates the other point if it is as good or better in
    all the dimensions. For example Roadster with mileage=20 and seating=2 dominates
    Ferrari F1 with mileage=10 and seating=1. This condition can certainly be
    expressed in SQL. In our example, the Skyline query is
    select * from Cars c
    where not exists (
    select * from Cars cc
    where cc.seats >= c.seats and cc.mileage > c.mileage
    or cc.seats > c.seats and cc.mileage >= c.mileage
    Despite apparent simplicity of this query, you I'm not pleased with this query
    performance. Even if we index the seats and mileage columns, this wouldn’t help
    much as only half of the records on average meet each individual inequality
    condition. Certainly, there aren’t many records that satisfy the combined
    predicate, but we can’t leverage index to match it. Bitmapped indexes, which
    excel with Boolean expressions similar to what we have, demand a constant on one
    side of the inequality predicate.
    There is an efficient way to answer Skyline query. Order all the data by either
    seats, mileage, or mileage, seats. Here a composite index might be handy.
    Compare each record with its predecessor, and discard the one that is dominated
    by the other. Let’s assume that our example has been extended to 4 records:
    MANUFACTURER SEATS MILEAGE
    Hummer 4 5
    Ferrari 1 10
    BMW 2 15
    Roadster 2 20
    Iterating record by record down, Ferrari would be excluded first, because it’s
    dominated by the neighbor BMW. Then, BMW itself would be excluded, because it’s
    dominated by Roadster.
    The challenge is to express this algorithm (efficiently) in SQL. With or without Analytics.

    Mike:
    Performance aside, see if you can reproduce:
    Connected to:
    Oracle9i Enterprise Edition Release 9.2.0.6.0 - Production
    With the Partitioning, Oracle Label Security, OLAP and Oracle Data Mining options
    JServer Release 9.2.0.6.0 - Production
    flip@FLOP> CREATE TABLE CARS
      2  (
      3  MANUFACTURER VARCHAR2(10 BYTE),
      4  SEATS NUMBER(2),
      5  MILEAGE NUMBER
      6  );
    Table created.
    Elapsed: 00:00:00.00
    flip@FLOP>
    flip@FLOP> insert into cars
      2  select to_char(object_id) , mod(object_id,7)+1, mod(object_id,25)+25
      3  from   all_objects where rownum < 101;
    100 rows created.
    Elapsed: 00:00:00.00
    flip@FLOP>
    flip@FLOP> insert into cars
      2  select 'x'||manufacturer, seats, mileage
      3  from    cars;
    100 rows created.
    Elapsed: 00:00:00.00
    flip@FLOP>
    flip@FLOP> commit;
    Commit complete.
    Elapsed: 00:00:00.00
    flip@FLOP>
    flip@FLOP> CREATE OR REPLACE FORCE VIEW CARS_VIEW
      2  (MANUFACTURER,SEATS, MILEAGE, LVL, RNM, SKLN_FLG)
      3  AS
      4  select
      5  MANUFACTURER,
      6  seats,
      7  mileage,
      8  level lvl,
      9  rownum rnm,
    10  (
    11  case when level=rownum then 1
    12  else 0
    13  end
    14  ) skln_flg
    15  from
    16  (
    17  select
    18  MANUFACTURER,
    19  seats,
    20  mileage
    21  from cars
    22  order by mileage desc
    23  )
    24  connect by prior seats < seats ;
    View created.
    Elapsed: 00:00:00.00
    flip@FLOP>
    flip@FLOP> select
      2  c.* from cars c,
      3  (
      4  select mileage,seats from cars_view where rownum <
      5  (
      6  select rnm from cars_view
      7  where skln_flg=0
      8  and rownum < 2
      9  )
    10  )sbq
    11  where c.mileage = sbq.mileage
    12  and c.seats = sbq.seats
    13  ;
    MANUFACTUR      SEATS    MILEAGE
    9849                1         49
    x9849               1         49
    9249                3         49
    x9249               3         49
    x22724              3         49
    22724               3         49
    14424               5         49
    x14424              5         49
    15174               6         49
    x15174              6         49
    7349                7         49
    x7349               7         49
    12 rows selected.
    Elapsed: 00:00:00.00
    flip@FLOP>
    flip@FLOP> select * from Cars c
      2  where not exists (
      3  select * from Cars cc
      4  where cc.seats >= c.seats and cc.mileage > c.mileage
      5  or cc.seats > c.seats and cc.mileage >= c.mileage
      6  );
    MANUFACTUR      SEATS    MILEAGE
    7349                7         49
    x7349               7         49
    Elapsed: 00:00:00.00
    flip@FLOP>

  • Regression parameters

    Hi,
    I have some questions regarding regression. I don't have wide knowledge in statistics - I'm rather technician (so sorry if questions are obvious for analysts).
    I'm investigating ODM and trying to understand background of regression in ODM.
    1. How regression algorithm predicts values of parameters for regression (SVM) in ODM ??
    If I'm launching model in workflow it automatically calculates some values to complexity factor, svms_epsilon, std_dev, etc. How it is calculated ??
    2. What is a measure of best algorithm ?? Minimal RMSE and MAE ??
    If minimal RMSE and MAE, then automatic calculation gives poor results.
    3. I checked several combination of parameters and concluded, that the best fit to my original data (minimal RMSE and MAE) is for gaussian svm when is:
    minimal epsilon, minimal deviation and maximal complexity factor.
    But I think that parameters strictly fits to input data and does not follow "random factor" (because of minimal deviation).
    How to check what are optimal values for regression parameters ??
    4. How to calculate "predictive confidence" of regression algorithm using ODM SQL? In workflow it is calculated automaticaly, in ODM SQL I didn't found possibility to show this measure.
    Thanks in advance,
    Paul.

    Perhaps you might want to sign up for the new 2 day Instructor Led Oracle University Course on Oracle Data Mining? It helps to answer these and many similar questions. See blog entry https://blogs.oracle.com/datamining/entry/new_2_day_instructor_led
    Also, the ODM Docs are posted on-line so you can always search them for more detailed answeres. [Others may respond w/ specific details to your questions.  I wanted to make you aware of the great learning resource as you said that you were new to the field.  Best of luck!]

  • Run Rebuild Index Task daily on database but about 77 tables still highly fragmented over 80% !!!

    Hello everyone
    On our particular database server, we run the Rebuild Index Task (Using classic Maintenance Plan Designer) every night. Running the  script below, I saw that about 77 tables had an avg_fragmentation_in_percentage between 80% and 99% !!
    SELECT OBJECT_NAME(ind.OBJECT_ID) AS TableName,
    ind.name AS IndexName, indexstats.index_type_desc AS IndexType,
    indexstats.avg_fragmentation_in_percent
    FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, NULL) indexstats
    INNER JOIN sys.indexes ind
    ON ind.object_id = indexstats.object_id
    AND ind.index_id = indexstats.index_id
    WHERE indexstats.avg_fragmentation_in_percent > 30--You can specify the percent as you want
    ORDER BY indexstats.avg_fragmentation_in_percent DESC
    I dont understand why these tables are highly fragmented after a daily index rebuild! Unless the users are doing heavy inserts/updates/deletes during the day.
    Anyone has an idea of the possible causes of these results??
    Thank you all in advance

    Hallo Efyuzegeekgurl,
    this is a normal behaviour when your table is only a small one. The reason for that behaviour is the following:
    The dmv sys.dm_db_index_physical_stats counts each page which is not located at the very next one of the same table as a "fragment". If the first data page is 1700 and the second one is located on 1705 SQL server will count it as a fragment.
    The basic allocation algorithm of Microsoft SQL Server is that new data pages will be created in "mixed extents". An extent is a contigious line of 8 consecutive data pages. This is for historical reasons when storage was expensive and data should
    use as much as possible of allocated storage.
    If a new table will be created the very first 8 pages are not located one after the other but "could" be located on different extents. If your table has only 9 data pages than 8 pages will count as "fragmented" because of their non consecutive
    allocation. After 8 pages have been allocated Microsoft SQL Server will ALWAYS use a full extent for the next 8 pages (and so on!).
    To understand this behaviour use the following example which creates a table with a record length of 8K. The next command will create 10 records (which means 10 data pages).
    CREATE TABLE dbo.foo
    Id INT NOT NULL IDENTITY (1, 1),
    c1 CHAR(8000) NOT NULL DEFAULT ('filler')
    GO
    SET NOCOUNT ON;
    GO
    INSERT INTO dbo.foo DEFAULT VALUES
    GO 10
    When you check the page allocation you'll find the first 8 data pages not in a consecutive row but "scrambled" into different pages:
    SELECT database_id,
    index_id,
    partition_id,
    allocation_unit_type_desc,
    extent_page_id,
    allocated_page_page_id,
    is_mixed_page_allocation,
    page_type_desc
    FROM sys.dm_db_database_page_allocations
    DB_ID(),
    OBJECT_ID('dbo.foo', 'U'),
    0,
    NULL,
    'DETAILED'
    ) AS DDDPA
    WHERE
    DDDPA.is_allocated = 1
    ORDER BY
    DDDPA.is_iam_page DESC,
    DDDPA.page_level DESC;
    GO
    You will see that the first 8 pages are located in a MIXED extent. Although the pages are in a consecutive order in the extent 221112 it is not guaranteed!
    You can see from the very first three records that they are not in a consecutive row stored.
    Now the fragmentation of the data seems to be quite high because we have 4 breaks in the rows. If we compare this value to the "fragmentation in sys.dm_db_index_physical_stats we will see at least the same result:
    SELECT index_type_desc,
    alloc_unit_type_desc,
    DDIPS.avg_fragmentation_in_percent,
    DDIPS.fragment_count,
    DDIPS.page_count,
    avg_page_space_used_in_percent
    FROM sys.dm_db_index_physical_stats
    DB_ID(),
    OBJECT_ID('dbo.foo', 'U'),
    NULL,
    NULL,
    'DETAILED'
    ) AS DDIPS;
    So - just from my point of view - don't count only to the fragmentation in percent because if the table is to small it will ALWAYS be over 30%. Take more into account the density of the pages and - as all others have mentioned - the number of pages of the
    index.
    I would consider indexes with more or equal to 1.000 pages.
    Another tip: Forget about the f... maintenance plans. These "plans" are not worth the time and money because you cannot control it in a more precise way. Have a look to the solution of Ola Hallengren and implement his solution - a great master
    piece of index maintenance:
    http://ola.hallengren.com
    All the best to the community :)
    MCM - SQL Server 2008
    MCSE - SQL Server 2012
    db Berater GmbH
    SQL Server Blog (german only)

  • PL-SQL procedure to fix Recycle Algorithm issues with Advanced Outbound

    Dear all,
    A customer is using Oracle Advanced Outbound 11.5.9. and we have an issue with recycle Algorithm.
    The issue is that for some cases we get outcome 32, 37 which is cache expired in table iec_g_return_entries and not the original outcome that agent has entered.
    Fortunately the original outcome exists in table jtf_ih_interactions so we have created a workaround in PL-SQL to update table iec_g_return_entries from jtf_ih_interactions using some common outcomes.
    Now after a long time the issue still exists and the customer want this workaround to be optimized, so that it takes all the values from recycle algorithm tables and not just the common outcomes and conditions.
    As I can see, there are so many condition in the algorithms and it is quite hard to catch all the conditions and create an PL-SQL procedure to update the iec_g_return_tables.
    Has anyone done something similar?
    Thanks a lot,
    Christos

    Dear all,
    A customer is using Oracle Advanced Outbound 11.5.9. and we have an issue with recycle Algorithm.
    The issue is that for some cases we get outcome 32, 37 which is cache expired in table iec_g_return_entries and not the original outcome that agent has entered.
    Fortunately the original outcome exists in table jtf_ih_interactions so we have created a workaround in PL-SQL to update table iec_g_return_entries from jtf_ih_interactions using some common outcomes.
    Now after a long time the issue still exists and the customer want this workaround to be optimized, so that it takes all the values from recycle algorithm tables and not just the common outcomes and conditions.
    As I can see, there are so many condition in the algorithms and it is quite hard to catch all the conditions and create an PL-SQL procedure to update the iec_g_return_tables.
    Has anyone done something similar?
    Thanks a lot,
    Christos

  • Need help with SQL algorithm

    table structure
    Column Data __Type
    game_id______Integer
    home_team___String
    away_team___String
    home_score___Integer
    away_score___Integer
    game_note____String
    The XML document should be displayed as:
    <lacrosse>
    <title>College Lacrosse Results</title>
    _<team>
    ____team_name
    ____<wins>number of wins</wins>
    ____<losses>number of losses</losses>
    ____<opponent>
    _________opponent_name
    _________<location>home or away</location>
    _________<for>goals scored</for>
    _________<against>goals given up</against>
    ____</opponent>
    ____<opponent>
    ____</opponent>
    _</team>
    _<team>
    _</team>
    </lacrosse>
    I'm not really sure what my Statements to query the database should be.
    My code so far is as such:
    import java.sql.*;
    import java.io.*;
    import org.w3c.dom.*;
    import org.apache.xerces.dom.*;
    import org.apache.xml.serialize.*;
    import javax.xml.*;
    import org.apache.xml.serialize.OutputFormat;
    public class DBtoXML {
         public static final String DB_URL = "jdbc:mysql://localhost/test";
         public static final String DRIVER = "com.mysql.jdbc.Driver";
         public static final String USERNAME = "'keith'@'localhost'";
         public static final String PASSWORD = "keith";
         public static final String OUTPUTFILE = "C:\\Test.xml";
         public static final String SQL1 = "";
         * @param args
         public static void main(String[] args)
         throws ClassNotFoundException
              // make JDBC connection with Xerxes
              try
                   Class.forName(DRIVER).newInstance();
                   Connection connection = DriverManager.getConnection(DB_URL);
                   // retrieve query result from database, store in ResultSet object
                   Statement statement = connection.createStatement();
                   ResultSet resultSet = statement.executeQuery(SQL1);
                   // build scores XML DOM
                   Document xmlDoc = buildScoresXML(resultSet);
                   // write to flat file
                   File outputFile = new File(OUTPUTFILE);
                   printDOM(xmlDoc, outputFile);
                   connection.close();
              catch (InstantiationException ie)
                   ie.printStackTrace();
              catch (SQLException sqle)
                   sqle.printStackTrace();
              catch (IllegalAccessException iae)
                   System.out.println("Error generating connection: " + iae);
              catch (Exception e)
                   System.out.println(e);
         } //end main()
         * buildScoresXML() - build Document from MySQL database
         * @param resultSet
         * @return - XML object to main() to be written to flat file
         * @throws Exception
         private static Document buildScoresXML(ResultSet rs)
         throws Exception
              Document xmlDoc = new DocumentImpl();
              // create root element
              Element rootElement = xmlDoc.createElement("lacrosse"); //has children
              xmlDoc.appendChild(rootElement);
              while(rs.next())
                   // create elements child elements of lacrosse (title, team)
                   Element title = xmlDoc.createElement("title");
                   rootElement.appendChild(title);
                   Element team = xmlDoc.createElement("team"); //has children
                   rootElement.appendChild(team);
                   // create child elements of team (wins, losses, opponent)
                   Element wins = xmlDoc.createElement("wins");
                   team.appendChild(wins);
                   Element losses = xmlDoc.createElement("losses");
                   team.appendChild(losses);
                   Element opponent = xmlDoc.createElement("opponent"); //has children
                   team.appendChild(opponent);
                   // create child elements of opponent (location, for, against)
                   Element location = xmlDoc.createElement("location");
                   opponent.appendChild(location);
                   Element goalsFor = xmlDoc.createElement("for");
                   opponent.appendChild(goalsFor);
                   Element against = xmlDoc.createElement("against");
                   opponent.appendChild(against);
              return xmlDoc;
         } //end buildScoresXML()
         * printDOM() - write contents of XML document passed onto it to a file
         * @param xmlDoc
         * @param outputFile
         * @throws Exception
         private static void printDOM(Document xmlDoc, File outputFile)
         throws Exception
              OutputFormat outputFormat = new OutputFormat("XML", "UTF-8", true);
              FileWriter fileWriter = new FileWriter(outputFile);
              XMLSerializer xmlSerializer = new XMLSerializer(fileWriter, outputFormat);
              xmlSerializer.asDOMSerializer();
              xmlSerializer.serialize(xmlDoc.getDocumentElement());
    } // end DBtoXML
    Not sure where to go from here
    Edited by: habituallinecrosser on Mar 23, 2009 2:10 PM

    I apologize for that scatter-brained, half-arsed post there =(
    It's not becoming of me to clutter the board with that, nor to be so vague.
    Anyway...
    Briefly, the requirements for this assignment are:
    To create the an XML document in the above format, using JDBC and DOM, from the data stored within the scores database, which contains the above listed fields.
    I have been supplied with a CSS file and an XSD file, too.
    My line of work is not software development, and I am not familiar with the XML APIs, nor JDBC.
    I'm somewhat thinking out loud here, but my approach would be:
    1. create a Team class with
    String name
    int wins
    int losses
    ArrayList games
    the inner class Games will have:
    String opponentName
    Enum location (home, away)
    int goalsScored
    int goalsAllowed
    2. create class TeamsLoader
    -will extract each individual team from the scores table (using a "select distinct home_team from scores", followed by query to pick up any teams that were only in away_team column) and add them to an ArrayList<Team>
    3. create class TeamRecordsCollector
    -will produce ResultSet of "select* from scores" statement
    -pass each index of ArrayList<Team> through each game_ID and compare team.Name with resultSet.home_team || resultSet.away_team for equality, and if equal, add the data to the Team
    5. create a Document (rootElement = lacrosse) and iterating through the ArrayList<team> using a loop, adding the Elements during the loop
    Is this making sense?
    6. wrap FileWriter, OutputFormat in XMLSerializer to create flat file

  • Break the algorithm through sql query

    Hi,
    My table 'x' contains data as follows:
    Row_id
    Person
    Effective_date
    Status
    Code
    1
    12345
    8-Apr-04
    POS
    A
    2
    12345
    13-Jun-04
    PLA
    P
    3
    12345
    20-Oct-04
    POS
    P
    4
    12345
    1-Apr-05
    PAY
    P
    5
    12345
    8-Aug-05
    RFL
    A
    6
    12345
    8-Aug-05
    XFR
    A
    7
    12345
    1-Apr-05
    PAY
    P
    Need this row as output
    8
    12345
    14-Jul-06
    LOA
    L
    9
    12345
    1-Oct-06
    PAY
    P
    10
    12345
    16-Jul-07
    LOA
    L
    11
    12345
    17-Jul-07
    RFL
    A
    Logic that should be used:
    1. Get the most recent row based on effective date and code in L or P-> In this case row 10 since this row has L and is latest one
    2. Then go back in time until the code is not in L or P -> so based on above data row 6 since the code is 'A'
    3. Then come forward from that record 6 until you get status LOA or PLA -> you will come and stand on row '8'
    4. finally i need the row_id = 8 as output based on the above steps
    Pls help me in framing a query for this

    Your effective dates are not unique, therefore it is impossible to decide which row with same effective date goes first. It is not possible to provide a deterministic solution until you define rules how to order rows with same effective date. Solution below is non-deterministic. Because you have rows with same effective date it can produce different results next time you run it. When you define ordering rules add them to ORDER BY clause of ROW_NUMBER function in below code. This will make it deterministic:
    with t1 as (
                select  e.*,
                        row_number() over(partition by emplid order by effective_start_date) rn
                  from  employee e
         t2 as (
                select  t1.*,
                        max(
                            case
                              when code in ('L','P') then rn
                            end
                          over(partition by emplid) last_l_p_rn,
                        last_value(
                                   case
                                      when code not in ('L','P') then rn
                                   end
                                   ignore nulls
                          over(partition by emplid order by rn) last_non_l_p_rn,
                        first_value(
                                    case
                                       when status in ('LOA','PLA') then rn
                                   end
                                   ignore nulls
                          over(
                               partition by emplid
                               order by rn
                               rows between current row and unbounded following
                             ) first_loa_pla_rn
                  from  t1
    select  emplid,
            effective_start_date,
            status,
            code
      from  t2
      where level = 3
      start with rn = last_l_p_rn
      connect by (emplid = prior emplid and rn = prior last_non_l_p_rn and level = 2)
              or (emplid = prior emplid and rn = prior first_loa_pla_rn and level = 3)
    EMPLID     EFFECTIVE STA C
    12345      14-JUL-06 LOA L
    SQL>
    SY.

  • Algorithm for Unix crypt function in PL*SQL

    Does anyone have similar sample in PL*SQL that does what crypt
    function is doing in Unix (C)?
    man cryptReformatting page. Wait... done
    User Commands crypt(1)
    NAME
    crypt - encode or decode a file
    SYNOPSIS
    crypt [ password ]
    DESCRIPTION
    crypt encrypts and decrypts the contents of a file. crypt
    reads from the standard input and writes on the standard
    output. The password is a key that selects a particular
    transformation. If no password is given, crypt demands a
    key from the terminal and turns off printing while the key
    is being typed in. crypt encrypts and decrypts with the
    same key:
    Thanks,
    Frantz
    null

    The easiest way to accomplish this, is to just write an external
    PL/SQL wrapper function to directly call the crypt function.
    I've been working on code that does this already, including the
    generation of a random seed to generate the crypted password.
    Tom Tyson
    F.Sunjic (guest) wrote:
    : Does anyone have similar sample in PL*SQL that does what crypt
    : function is doing in Unix (C)?
    : > man crypt
    : Reformatting page. Wait... done
    : User Commands crypt
    (1)
    : NAME
    : crypt - encode or decode a file
    : SYNOPSIS
    : crypt [ password ]
    : DESCRIPTION
    : crypt encrypts and decrypts the contents of a file.
    crypt
    : reads from the standard input and writes on the
    standard
    : output. The password is a key that selects a
    particular
    : transformation. If no password is given, crypt
    demands a
    : key from the terminal and turns off printing while the
    key
    : is being typed in. crypt encrypts and decrypts with
    the
    : same key:
    : Thanks,
    : Frantz
    null

  • K-anonymity algorithm in sql

    Hi,
    does anyone have information on how to implemend k-anonymity algorithm with oracle or soemthing relevant?
    I would be thankful if someone could help me.

    I do not know if this helps, but you may want to try to use datapump
    expdp remap_data=table_name.column_name:pkg.function ...
    http://download.oracle.com/docs/cd/B28359_01/server.111/b28319/dp_export.htm#BABDCEDA
    well, it is not possible in 10.2

Maybe you are looking for

  • Help please - template problems

    2 questions please - actually: 1.  Dreamweaver CS4... I think my template functionality has somehow become corrupted.  When I try to create new templates (regardless of which site I'm trying it within), they look ok.  But when I then try to create a

  • Configure a single ODI install for multiple Data Sources in ERPI

    I am setting up multiple data sources in ERPI to point to different EBS instances. How would I go about setting up ODI to support that without multiple installations of ODI? or is multiple installs the best way to go, from an 'ease of management' per

  • HELP WITH CREATING A VIEW USING PL/SQL

    Hello, I have two tables, one is simply an audit version of the other and anytime data is updated, modified, or deleted the data is copied to the audit table (via a trigger) and the audit table records who made the changes and when. Here is the descr

  • Recently updated records to be sent back

    Hi, procedure(i_dept in number, dept_cur out sys_refcursor) is begin update emp set sal=sal+100 where dept=i_dept; end; in this procedure i want to send only the updated records back in dept_cur cursor. lets say in 1st proc call 2 records updatd then

  • About gather statistics - ANALYZE on Oracle views

    Oracle® Database Reference 11g Release 1 (11.1) Part Number B28320-01 ALL_TABLES describes the relational tables accessible to the current user. To gather statistics for this view, use the ANALYZE SQL statement. Columns marked with an asterisk (*) ar