Tricky Regexp and string to column-row SQL
Hi All,
I am TRYING to build an SQL that will convert a string passed as
HP|250 GB * 2 + 80 GB * 3 + 100 GB | SATAto
HP | 250 GB | SATA
HP | 250 GB | SATA
HP | 80 GB | SATA
HP | 80 GB | SATA
HP | 80 GB | SATA
HP | 100 GB | SATAMy attempt so far is (which tells me to learn more about regexp)
WITH T AS
( SELECT q'[HP|250 GB * 2 + 80 GB * 3 + 100 GB | SATA]' str FROM DUAL
t2 AS
(SELECT trim(regexp_substr(str,'[^|]+',1,level)) val
FROM T
CONNECT BY level <= LENGTH (str)-LENGTH(REPLACE(str,'|'))+1
),t3 AS
(SELECT DISTINCT trim(regexp_substr(val,'[^+]+',1,level)) val
FROM t2 WHERE VAL LIKE '%*%' OR VAL LIKE '%+%'
CONNECT BY level <= LENGTH (val)-LENGTH(REPLACE(val,'+'))+1
),t4 as
(SELECT VAL,ROWNUM RN FROM T2 A1
WHERE VAL NOT LIKE '%*%' OR VAL NOT LIKE '%+%'),
t5 as
(SELECT A.VAL MK, T3.VAL CONFG, B.VAL TYP
FROM T3, (SELECT VAL FROM T4 WHERE RN = 1)A,(SELECT VAL FROM T4 WHERE RN = 2) B)
SELECT *
FROM T5;And output I got so far is:
MK CONFG TYP
HP 80 GB * 3 SATA
HP 250 GB * 2 SATA
HP 100 GB SATA Please suggest what more shall I do to get the desired output(An SQL)?
BANNER
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
PL/SQL Release 11.2.0.1.0 - Production
CORE 11.2.0.1.0 Production
TNS for 32-bit Windows: Version 11.2.0.1.0 - Production
NLSRTL Version 11.2.0.1.0 - Production Thanks for reading this post
*009*
with t1 as (
select 'HP|250 GB * 2 + 80 GB * 3 + 100 GB | SATA' str from dual union all
select 'INTEL|40 GB + 55 GB| IDE' from dual
t2 as (
select regexp_substr(str,'^[^|]+') mk,
trim(regexp_substr(replace(str,'|','+'),'[^+]+',1,column_value + 1)) element,
regexp_substr(str,'[^|]+$') typ
from t1,
table(
cast(
multiset(
select level
from dual
connect by level <= length(regexp_replace(str || '+','[^+]'))
as sys.OdciNumberList
select mk,
trim(regexp_replace(element,'\*.*$')) val,
typ
from t2,
table(
cast(
multiset(
select level
from dual
connect by level <= substr(regexp_substr(element,'\*.*$'),2)
as sys.OdciNumberList
MK VAL TYP
HP 250 GB SATA
HP 250 GB SATA
HP 80 GB SATA
HP 80 GB SATA
HP 80 GB SATA
HP 100 GB SATA
INTEL 40 GB IDE
INTEL 55 GB IDE
8 rows selected.
SQL> SY.
P.S. Post your version. If 11.1 it can be simplified. If 11.2 can be simplified even more.
Similar Messages
-
How to Plot number and string in one row (data logger counter) ?
hi all i made data log quantity using Digital Counter via modbus to monitoring quantity and reject that has and Name Operator, Machine and Part Number.
i have problem about plot the number & string in one row, as shown on the picture below :
how to move that string on one row ? i attach my vi.
Thanks~
Attachments:
MODBUS LIB Counter.vi 39 KBDuplicate and answered - http://forums.ni.com/t5/LabVIEW/How-to-Plot-number-and-string-in-one-row-data-logger-counter-via/m-p...
-
How to Plot number and string in one row (data logger counter via MODBUS) ?
hi all i made data log quantity using Digital Counter via modbus (RS-485) to monitoring quantity and reject that has and Name Operator, Machine and Part Number.
i have problem about plot the number & string in one row, as shown on the picture below :
how to move that string on one row ? i attach my vi.
Thanks~
Solved!
Go to Solution.
Attachments:
MODBUS LIB Counter.vi 39 KBHi rhiesnand,
right now you add 2 new rows to your array.
The solution is to concatenate both row parts to one bigger 1D array before adding that array as new row to your 2D array!
Like this:
Best regards,
GerdW
CLAD, using 2009SP1 + LV2011SP1 + LV2014SP1 on WinXP+Win7+cRIO
Kudos are welcome -
How to programatically select a row in TableBean and update its column?
Hi,
Can anyone help me on How to programmatically select a row in a TableBean and update its column?
Thanks,
JonHi,
My requirement is I need to update a column in a particular row of the table using fire action...
I have a datefield bean serve as birhdate and base on this I need to update the age column depending on the given dates..
Here's my code under the Process form request for your reference...
if (actionInMainPersonScreen.equals("changeDate"))
String checkId = pageContext.getParameter("paramDatePersonId");
OAFormValueBean depPerId = (OAFormValueBean)depTable.findIndexedChildRecursive("ChildPersonID");
OAMessageTextInputBean depFName = (OAMessageTextInputBean)depTable.findIndexedChildRecursive("FirstName");
OAMessageDateFieldBean dateBirth = (OAMessageDateFieldBean)depTable.findIndexedChildRecursive("BDay");
OAMessageStyledTextBean age = (OAMessageStyledTextBean)depTable.findIndexedChildRecursive("Age");
Date changeBDate = new java.util.Date();
Date dateToday = new java.util.Date();
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
changeBDate = (Date)dateBirth.getValue(pageContext);
Calendar cal = Calendar.getInstance();
ResultSet empAge = null;
String newAge = null;
OADBTransaction trans = personam.getOADBTransaction();
System.out.println("BirthDate: " + changeBDate + " Date Today: " + sdf.format(dateToday));
String expQuery = "SELECT Trunc((sysdate - To_Date('" + pageContext.getParameter("paramDateBirth") + "'))/365) compAge, Sysdate from dual";
System.out.println("SQL: " + expQuery);
PreparedStatement expPreparedStatement = trans.createPreparedStatement(expQuery ,1);
try
empAge = expPreparedStatement.executeQuery();
} catch (SQLException e) {}
try
while (empAge.next())
newAge = empAge.getString("compAge");
age.setText(pageContext, newAge);
empAge.close();
} catch (SQLException e) {}
regards,
Jon -
Hi,
How can i convert rows to column in sql
I have table with the two columns child_table_name and parent_table_name as below. How can convert the below table to the expected output. show all the child and corresponding parent_table in one row. Please help to write sql
Child_table_Name Parent_Table_name
abc bbb
abc aaa
def ccc
def ttt
Expected Output
abc bbb aaa
def ccc ttt
Thanks,
ChHi,
That's called a Pivot, and here's one way to do it:
WITH got_r_num AS
SELECT child_table_name
, parent_table_name
, ROW_NUMBER () OVER ( PARTITION BY child_table_name
ORDER BY parent_table_name
) AS r_num
FROM table_x
SELECT *
FROM got_r_num
PIVOT ( MAX (parent_table_name)
FOR r_num IN ( 1 AS parent_1
, 2 AS parent_2
, 3 AS parent_3
The forum FAQ has a page devoted to pivots:
https://forums.oracle.com/message/9362005#9362005
The query above can show up to 3 parents per child. If you know you'll never have more than 2 (as in your message) then you don't need the line that defines parent_3. On the other hand, if you might need more than 3 parents, you can add as many more as you need.
I hope this answers your question.
If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all tables involved, and also post the results you want from that data.
Point out where the statement above is getting the wrong results, and explain, using specific examples, how you get the right results from the given data in those places. Remember that there is no built-in order to the rows in a table, so if your explanationuses words like "first" or "latest", define what they mean in terms of the data in your table.
Always say which version of Oracle you're using (e.g., 11.2.0.2.0).
See the forum FAQ: https://forums.oracle.com/message/9362002 -
Web Service to Query with 21 Columns and up to 1000 Rows
Hi Experts,
I have a web service to a query that returns a table of 21 Columns and up to 1000 Rows.
I would like to display this data in an UI element such List view / Spreadsheet table.
When I am doing so, I have the following issues:
1. With the Spreadsheet table I can't set the header of the columns to the name of the column in the query.
2. with both elements I would like to have a paging capability which I am not sure if is even possible.
3. With both elements I am not able to set the width of each column as I need, and also not able to define the correct formating (date / string....)
Is it possible to have what I am looking for with these elements? Or there are other UI elements for it?
Thanks in advanced,
DoronSHi Charles,
Actually, I am using Xcelsius as you said, and wanted to use it also as I mentioned since in the Web Intelligence I could not find the way to have a good filtering mechanism.
Meaning, there is an option to add filters based on the fields that are in the query. But you can only choose one value per filter filed. If I want filter the data with more than one value it is impossible. Furthermore, there is no way to use free text filtering.
Do you know in what BO Tool I will be able to provide such filtering capabilities?
DoronS -
How to convert rows to columns in sql server 2008
How to convert rows to columns in sql server 2008 using the GROUP BY function? (only one query allowed)
Lookup the Pivot transformation. From BOL:
The Pivot transformation makes a normalized data set into a less normalized
but more compact version by pivoting the input data on a column value. For
example, a normalized Orders data set that lists customer name, product, and quantity purchased typically has multiple rows for any customer who purchased multiple products, with each row for that customer showing order
details for a different product. By pivoting the data set on the product column, the Pivot transformation can output a data set with a
single row per customer. That single row lists all the purchases by the customer, with the product names shown as column names, and the quantity shown as a value in the product column. Because not every customer purchases every product, many columns may contain
null values.
When a dataset is pivoted, input columns perform different roles in the pivoting process. A column can participate in the following ways:
The column is passed through unchanged to the output. Because many input rows
can result only in one output row, the transformation copies only the first
input value for the column.
The column acts as the key or part of the key that identifies a set of
records.
The column defines the pivot. The values in this column are associated with
columns in the pivoted dataset.
The column contains values that are placed in the columns that the pivot
creates.
Paul -
I have done extensive programming with the SQL Toolkit with LabVIEW versions through 6.1. My customer now wants to upgrade to Windows 7, so I am trying to upgrade to LabVIEW 2009 (my latest purchased version) using the Database Connectivity Toolkit, and the SQL Toolkit Compatibility vis. Everything seemed to be going okay with the higher level SQL operations, but I ran into trouble with the Get Column Name.vi.
The pictures below show the problem. The original SQL Toolkit connected the Prepare SQL.vi with the Get Column Name.vi with a cluster of two references, one for connection, and one for sql. The new compatibility vis have a class conflict in the wire because the Prepare SQL.vi contains a cluster with connection, and command references, but the Get Column Name.vi expects a cluster with connection and recordset references.
How do I resolve this conflict?
Thank You.
DanI've never worked with the old version of the toolkit, so I don't know how it did things, but looking inside the SQL prep VI, it only generates a command, and the the column name VI wants a recordset. I'm not super familiar with all the internals of ADO, but my understanding is that is standard - you only have the columns after you execute the command and get the recordset back. What you can apparently do here is insert the Execute Prepared SQL VI in the middle and that will return what you need.
I'm not sure why it worked before. Maybe the execute was hidden inside the prep VI or maybe you can get the column names out of the command object before execution. In general, I would recommend considering switching to the newer VIs.
Try to take over the world! -
How do I get the Layout Guides (A,B,C column headers and 1,2,3 Row Headers) to print on my spreadsheet? They are invaluable for discussing the data with my clients over the phone.
They appear while I am editing, but don't print with the spreadsheet. I know how to do it in Excel, but I am transitioning to Numbers. I can't imagine I have to type them into their own columns and rows. It must be a difference in vernacular that I can't find the solution in the User Guide. Can anyone help?Hi ktjobauer,
Numbers is not Excel and Excel is not Numbers. Numbers is WYSIWYG (at least in File > Print and the actual printout).
I can't imagine I have to type them into their own columns and rows.
No, you don't. You can use the charm of Numbers to create cell references for your Excel clients.
In this Numbers Table, I have added some extra Columns that you can hide later.
Column B =COLUMN(A2)
Column C =HLOOKUP(B2,'Table 1-1' :: $1:$2,2,FALSE) [explanation later]
Column D =ROW(B2)
Column E =C2&D2
Add those formulas to the first Body Row (below the Header Row) and Fill Down.
Column C refers to another Table which you need only create once, to convert a Column number to a letter:
and so on from 1-26, A-Z.
You can move the second Table to another Sheet to hide it. Formulas will automatically adjust to keep the links between Sheets.
Now in the first Table, select and Hide Columns B,C,D. Formulas will continue to work with hidden cells:
Regards,
Ian. -
We used to be able to sort by multiple columns/rows at once by right clicking on the header and choosing show more options-how do we do that in the new Numbers? It doesn't appear anywhere. Do I now have to sort massive tables by each column one at a time now? Also there used to be an easier way to merge/unmerge cells without me having to go to the table menu each time. Am I missing something?
Multiple column sort is a missing feature in the new version. Hopefully soon to return. You can do a multicolumn sort by sorting one at a time in reverse order of importance.
For merging and unmerging cells, I select the cells and right click to bring up the contextual menu. Merge and unmerge are on the menu. You could also create keyboard shortcuts for Merge Cells and Unmerge Cells in the Table menu. -
Problem with Column types and String
Hi
I have some problem while comparing against empty string.
My column is of type it_Linked_Button. Actually it seems that column type doesn't matter.
If cell that belongs to this column is empty and based on other columns' values I put some value into this cell.
It works fine.
But when I clear that cell and try to put some value again nothing happens.
In my if statement I'm checking against empty string and it fails second time.
Before I put anything in that cell (in debugger) that value is "" so it is empty and it works.
(OK, I see that after I posted this message it was slightly reformated)
But after I put something and clear that cell and try to put something again (in debugger) I get "(here is some long space) " which fails String.IsNullOrEmpty(var) test.
What is going on? Has it something to do with Column type?
How to clear it so I can put something in it again?
One more thing - to put values and clear it I use DbDataSource SetValue method. And String.Empty or ""(doesn't matter)
Thanks
Kamil
NOTE
I made some workaround that gives me the behaviour I want but still I would like to know what is going on?
Edited by: Kamil Wydrzycki on Sep 24, 2009 12:57 PMDrLaszloJamf wrote:
warnerja wrote:
DrLaszloJamf wrote:
1. Could you define an Enum? Then you could switch on enum values.
2. Wait for Java 7 which is supposed to extend switch to strings?3. Put the target strings in a collection, write a loop to find the match in the collection and use the matching index in the switch statement. At least that will get rid of the hashcode kludge, where it won't mistakenly 'match' a string which isn't the actual target.3b: Map<String, Command>Yep.
I also wanted to point this out to the OP:
For example, let's say the 7 character string "BugABoo" happens to have the same hashcode as "EDI_DOC". And let's say your input just happens to have the string "BugABoo" in it, where you're extracting the 7 character substring. See the problem? You're getting "BugABoo" but treating it as if it really were "EDI_DOC", by virtue of comparing hashcodes instead of actual strings.
OOPS! -
I've been trying to figure out the best way to calculate how many rows & columns of text can fit into a JTextPane. This is to be recalculated everytime the size of the JTextPane is changed or the font size has been changed. I've tried several different methods, but I can't seem to come up with anything consistent.
Has anyone here thought about or attempted anything like this? And how would you go about doing it?I'm feeling generous today... I think. Note that I haven't looked at this in quite awhile, but it should get you headed in the right direction. No promises on it's quality. :) If you have text wrapping turned on, that is where things get a bit tricky. This method basically tries to guess what a text area might do given the font, text and number of columns wide it is (or will be).
public static ArrayList CalcRows( String text, Font aFont, int columns ) {
ArrayList rows = new ArrayList();
try {
StyleContext sc = StyleContext.getDefaultStyleContext();
FontMetrics fm = sc.getFontMetrics( aFont );
StringBuffer buff = new StringBuffer();
for( int i = 0; i < columns; i++ ) {
buff.append( "w" );
// Estimated width of the columns is width of that many 'w' characters
int maxWidth = fm.stringWidth( buff.toString() );
// Iterate through the text & segments, and determine the lengths and
// breaks of the text to see how many rows it is
PlainDocument doc = new PlainDocument();
doc.insertString( 0, text, null );
Segment segment = new Segment();
int offset = 0;
while( offset < text.length() ) {
doc.getText( offset, text.length()-offset, segment );
int aBreak = Utilities.getBreakLocation( segment, fm, 0, maxWidth,
null, offset );
String aRow = text.substring( offset, offset + aBreak );
rows.add( aRow );
// The last break will be at the end of the text, check for it
if( offset + aBreak >= text.length() ) {
break;
offset = offset + aBreak;
} catch( Exception ex ) {
ex.printTrace(); // You should probably do something a bit more useful than this.
return rows;
} -
Setting and retrieving session using pl/sql
How to set and retrieve session using pl/sql?Can anyone help me?
mrs wrote:
create or replace
function get_login_details(in_user in VARCHAR2,in_pwd in VARCHAR2,in_cname in VARCHAR2)
..snipped..The code should look as follows:
create or replace function AuthenticateUser( userName varchar2, userPassw varchar2, userGroup varchar2 )
return integer is
i integer;
begin
--// purpose of the SQL is simply to check if such a row exist -
--// no data from the row needs to be fetched
select 1 into i from acl_users_gv
where user_name = userName
and password = userPassw
and entity_group_name = userGroup;
--// if the SQL succeeded, then the row exists and matches
--// the authentication details
return( 0 );
exception when NO_DATA_FOUND then
--// SQL failed to find a row - authentication details do
--// not exist
return( 1 );
end;No need to fetch data unnecessarily. No need too check the fetched data when the column values are already checked via the SQL filter condition (predicate).
No need to return a flag variable as a freely formatted text string containing Successful Login and login failed. That is not a robust design to use a string variable like that. Use boolean for true/false. Or use integer values 0/1.
This is my function get_login_details.And I need to get this 'o_mesg' in other java file also.Standard PL/SQL call from Java. The SQL string to execute contains an anonymous PL/SQL and needs to use bind variables. E.g.
begin
:result := AuthenticateUse( :userName, :userPassw, :userGroup );
end;
Can you suggest the right way, how I can get this variable in other pages?That depends on whether there is database session state. If there is, authentication can be done once only via a trusted context, that specifies whether the session is authenticated.
If this is done from an app server that uses a db session pool and stateless db sessions, the state needs to be kept in the app server.
Do you understand what stateful versus stateless db sessions are, and what the differences are? -
How to split the string by datetime in sql
Hi,
How to split the string by datetime in sql, I've a table with comments column stores comments by datetime, while selecting I want to split and show as in rows by each jobref.
can anyone help me in this please.
Thanks,declare @callcentre table (comments varchar(max),lbiref varchar(200))
insert into @callcentre
select '(28/10/2014 14:56:14) xyz ..... call logged (28/10/2014 14:56:58) xyz ..... call updated (28/10/2014 14:57:41)xyz ..... call updated','Vi2910201'
insert into @callcentre
select '(29/10/2014 14:56:14) xyz ..... call logged (29/10/2014 14:56:58) xyz ..... call updated (29/10/2014 14:57:41)xyz ..... call updated','Vi2910202'
insert into @callcentre
select '(30/10/2014 14:56:14) xyz ..... call logged (30/10/2014 14:56:58) xyz ..... call updated
output:
1) 28/10/2014 14:56:14, (28/10/2014 14:56:14) xyz ..... call logged ,'Vi2910201'
2) 28/10/2014 14:56:58 ,(28/10/2014 14:56:58) xyz ..... call updated ,'Vi2910201'
3) 28/10/2014 14:57:41, (28/10/2014 14:57:41)xyz ..... call updated,'Vi2910201'
4) 28/10/2014 14:56:14, (28/10/2014 14:56:14) xyz ..... call logged ,'Vi2910202'
5) 28/10/2014 14:56:58 ,(28/10/2014 14:56:58) xyz ..... call updated ,'Vi2910202'
6) 28/10/2014 14:57:41, (28/10/2014 14:57:41)xyz ..... call updated,'Vi2910202'
7) 28/10/2014 14:56:14, (28/10/2014 14:56:14) xyz ..... call logged ,'Vi2910203'
8) 28/10/2014 14:56:58 ,(28/10/2014 14:56:58) xyz ..... call updated ,'Vi2910203'
Thanks,
See this illustration
declare @callcentre table (comments varchar(max),lbiref varchar(200))
insert into @callcentre
select '(28/10/2014 14:56:14) xyz ..... call logged (28/10/2014 14:56:58) xyz ..... call updated (28/10/2014 14:57:41)xyz ..... call updated','Vi2910201'
insert into @callcentre
select '(29/10/2014 14:56:14) xyz ..... call logged (29/10/2014 14:56:58) xyz ..... call updated (29/10/2014 14:57:41)xyz ..... call updated','Vi2910202'
insert into @callcentre
select '(30/10/2014 14:56:14) xyz ..... call logged (30/10/2014 14:56:58) xyz ..... call updated','Vi2910203'
SELECT LEFT(p.u.value('.[1]','varchar(max)'),CHARINDEX(')',p.u.value('.[1]','varchar(max)'))-1) AS [Date],
'(' + p.u.value('.[1]','varchar(max)') AS comments,
lbiref
FROM
SELECT lbiref,CAST('<Root>' + STUFF(REPLACE(comments,'(','</Data><Data>'),1,7,'') + '</Data></Root>' AS XML) AS x
FROM @callcentre c
)t
CROSS APPLY x.nodes('/Root/Data')p(u)
and the output
Date comments lbiref
28/10/2014 14:56:14 (28/10/2014 14:56:14) xyz ..... call logged Vi2910201
28/10/2014 14:56:58 (28/10/2014 14:56:58) xyz ..... call updated Vi2910201
28/10/2014 14:57:41 (28/10/2014 14:57:41)xyz ..... call updated Vi2910201
29/10/2014 14:56:14 (29/10/2014 14:56:14) xyz ..... call logged Vi2910202
29/10/2014 14:56:58 (29/10/2014 14:56:58) xyz ..... call updated Vi2910202
29/10/2014 14:57:41 (29/10/2014 14:57:41)xyz ..... call updated Vi2910202
30/10/2014 14:56:14 (30/10/2014 14:56:14) xyz ..... call logged Vi2910203
30/10/2014 14:56:58 (30/10/2014 14:56:58) xyz ..... call updated Vi2910203
Please Mark This As Answer if it solved your issue
Please Mark This As Helpful if it helps to solve your issue
Visakh
My MSDN Page
My Personal Blog
My Facebook Page -
How to split strings into columns
Hi guys,
I have a select like this:
select 'testing1'||'.'||'testing2'||'.'||'testing3' from dualwhich gives me an output like this:
testing1.testing2.testing3How can I split this into 3 columns in SQL PLUS?
Thank you in advanceuser643734 wrote:
Thank you guys for all your help.
Hi,
I tried to resolve your problem using somme functions...
I know is a long, long story but it works.
Regards,
Ion--create table_pivot
CREATE TABLE pivot_table(id VARCHAR2(1) primary key, all_concat VARCHAR2(1810));
--add data
insert into pivot_table (id, all_concat) values('x','12345.2829303132.234234.234234.234234');
insert into pivot_table (id, all_concat) values('y','67890.2324252627.234234.234234.234234.332545');
insert into pivot_table (id, all_concat) values('z','11121314.12345.234234.234234.234234.23432.32453245.345435.345435');
insert into pivot_table (id, all_concat) values('a','151617.67890.234234.234234');
insert into pivot_table (id, all_concat) values('b','1819202122.1112131415.234234.234234.234234.345435');
insert into pivot_table (id, all_concat) values('c','2324252627');
insert into pivot_table (id, all_concat) values('h','2829303132.234234.234234.234234.23432.32453245.345435.345435.4325435.345');
insert into pivot_table (id, all_concat) values('r','');
set termout off
--procedures and functions to compile
--1. Main function to format strings
create or replace function fgetformatstring
(v_max_rows numeric, v_crt_row varchar2, v_table_source varchar2, v_save_to_table varchar2, v_option numeric)
return varchar2
is
v_crt_char numeric:=0;
v_pos_char numeric:=1;
v_count numeric:=0;
v_string_out varchar2(500);
v_str_paded varchar2(10):=',null';
v_length_pad numeric;
v_diff_pad numeric;
l_crt_row varchar2(1800);
v_char char:=',';
v_delimiter char:='.';
l_save_to_table varchar2(1000);
l_max_rows numeric;
begin
l_crt_row:=replace(v_crt_row,'.' ,',');
l_save_to_table:=v_save_to_table;
l_max_rows:=v_max_rows;
if v_option=0 then --get the ',null' to paded in pivot_table
loop
v_pos_char:=v_crt_char;
v_crt_char:=instr(v_crt_row,v_char, v_crt_char+1);
v_count:=v_count+1;
exit when v_crt_char=0 or v_count=1000;
end loop;
v_string_out:=' ';
v_count:=v_count-1;
v_diff_pad :=l_max_rows-1-v_count;
if v_diff_pad >0 then --nothing to add
v_length_pad:=length(v_str_paded);-- (+v_char)
v_length_pad:=v_diff_pad*v_length_pad;
v_length_pad:=v_length_pad+1;
v_string_out:=rpad(v_string_out,v_length_pad,v_str_paded);
end if;
end if;
if v_option=1 then --get definition of v_save_to_table
v_count:=1;
v_string_out:=' ';
loop
exit when v_count=l_max_rows+1 or v_count>=1000;
v_length_pad:=length(v_string_out||'col'||to_char(v_count)||',');
v_string_out:=rpad(v_string_out,v_length_pad,'col'||to_char(v_count)||',');
v_count:=v_count+1;
end loop;
v_string_out:=trim(v_char from v_string_out);
--v_string_out:='id,'||v_string_out;
v_string_out:=v_string_out;
end if;
if v_option=2 then --get position of last comma
loop
v_pos_char:=v_crt_char;
v_crt_char:=instr(v_crt_row,v_char, v_crt_char+1);
v_count:=v_count+1;
exit when v_crt_char=0 or v_count=1000;
end loop;
v_string_out:=substr(v_crt_row,1,v_pos_char-1);
end if;
if v_option=3 then --get numbers of delimiters(.)
loop
v_pos_char:=v_crt_char;
v_crt_char:=instr(v_crt_row,v_delimiter, v_crt_char+1);
--dbms_output.put_line( 'Rows: ' ||v_crt_row|| ' iteration: '||v_count);
v_count:=v_count+1;
exit when v_crt_char=0 or v_count=1000;
end loop;
v_count:=v_count;
v_string_out:=to_char(v_count);
end if;
if v_option=4 then --get sql command to create v_save_to_table
v_count:=1;
v_string_out:=' ';
loop
exit when v_count=l_max_rows+1 or v_count>=1000;
v_length_pad:=length(v_string_out||'col'||to_char(v_count)||' varchar2(40), ');
v_string_out:=rpad(v_string_out,v_length_pad,'col'||to_char(v_count)||' varchar2(40), ');
v_count:=v_count+1;
end loop;
v_string_out:=trim(' ' from v_string_out);
v_string_out:=trim(v_char from v_string_out);
v_string_out:='create table '|| l_save_to_table ||'('||v_string_out||')';
end if;
if v_option=5 then --get numbers of delimiters(,)
loop
v_pos_char:=v_crt_char;
v_crt_char:=instr(v_crt_row,',', v_crt_char+1);
v_count:=v_count+1;
exit when v_crt_char=0 or v_count=1000;
end loop;
v_count:=v_count-1;
v_string_out:=to_char(v_count);
end if;
dbms_output.put_line( 'string: ' ||v_string_out|| ' option: '||v_option);
return v_string_out;
end;
--2.get max items
create or replace function fgetmaxitems
--get the max number of items founded in the pivot_table.all_concat
--before change the points with comma
return numeric
is
v_max numeric:=0;
v_field pivot_table.all_concat%type;
v_crt_max numeric:=0;
v_crt_row varchar(1000);
cursor c1 is
select all_concat from pivot_table;
begin
v_crt_max:=0;
v_max:=0;
open c1;
loop
fetch c1 into v_field;
exit when c1%notfound;
v_crt_row:=v_field;
v_crt_max:=fgetformatstring(0,v_crt_row,'pivot_table','',3);
if v_crt_max>v_max then
v_max:=v_crt_max;
end if;
end loop;
close c1;
return v_max;
end;
--3. insert the rows in table_dest
create or replace procedure pinsertrow
v_max_rows numeric,
v_all_concat varchar2,
v_source_table_name varchar2,
v_save_to_tablename varchar2
is
v_sql_string varchar2(1000);
l_all_concat varchar2(1500);
begin
l_all_concat:=replace(v_all_concat,'.' ,',');
v_sql_string:='('||l_all_concat||')';
v_sql_string:=' insert into ' ||v_save_to_tablename
||' (' ||fgetformatstring(v_max_rows,l_all_concat,v_source_table_name,v_save_to_tablename,1)||')'||
' values'||v_sql_string ;
execute immediate v_sql_string;
end;
--4.procedure to create dinamically <table_dest>
create or replace procedure pcreatesavetable
(v_table_source varchar2, v_save_to_table varchar2)
is
v_sql_string varchar2(1000);
already_exists exception;
pragma exception_init(already_exists,-955);
v_max numeric;
begin
--clear empty values;
v_sql_string:='delete from ' ||v_table_source|| ' where length(all_concat)=0 or (all_concat) is null';
execute immediate v_sql_string;
v_sql_string:='';
v_max:=fgetmaxitems;
--create new table
v_sql_string:=fgetformatstring(v_max,'all_concat', v_table_source,v_save_to_table,4);
dbms_output.put_line( 'sql create : '|| v_sql_string);
execute immediate v_sql_string;
exception
when already_exists then
--delete old table
v_sql_string:='drop table ' ||v_save_to_table;
execute immediate v_sql_string;
--create new table
v_sql_string:=fgetformatstring(v_max,'all_concat', v_table_source,v_save_to_table,4);
dbms_output.put_line( 'sql recreate final_table : '|| v_sql_string);
execute immediate v_sql_string;
end;
--5.main procedure
create or replace procedure pmainproc(v_save_to_table varchar2)
is
v_key_pivot pivot_table.id%type;
v_column_pivot pivot_table.all_concat%type;
v_max numeric;
v_crt_row varchar2(1600);
cursor c2 is select y.id , y.all_concat
from pivot_table y
; --cursor upon pivot_table
begin
v_max:=fgetmaxitems;
if v_max <> 0 then
--clear empty values;
delete from pivot_table where length(all_concat)=0 or (all_concat) is null;
--change all points with comma
update
(select x.id, x.all_concat from pivot_table x, pivot_table y where x.id=y.id) b
set b.all_concat=replace(b.all_concat,'.', ',');
-- padd the all_concat with ',null'
update
(select x.id, x.all_concat from pivot_table x, pivot_table y where x.id=y.id and
fgetformatstring(v_max,x.all_concat,'pivot_table',v_save_to_table,5) <> v_max
) b
set b.all_concat=b.all_concat || fgetformatstring(v_max,b.all_concat,'pivot_table',v_save_to_table,0);
--remove last
update pivot_table
set all_concat= fgetformatstring(v_max,all_concat,'pivot_table',v_save_to_table,2)
where fgetformatstring(v_max,all_concat,'pivot_table',v_save_to_table,5) = v_max;
open c2;
loop
fetch c2 into v_key_pivot, v_column_pivot;
exit when c2%notfound;
v_crt_row:=v_column_pivot;
-- insert data in to final_table
pinsertrow(v_max,v_crt_row,'pivot_table',v_save_to_table);
end loop;
close c2;
end if;
end;
--create table_dest
--the table_dest will be created automatically, so you need admin privilege to run that before compile pcreatesavetable :
connect / as sysdba or connect system/password
--grant create table to hr;
--conne hr/hr;
exec pcreatesavetable('pivot_table','table_dest');
--add data to table_dest
exec pmainproc('table_dest');
set termout on
select * from table_dest;
Table created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
Function created.
Function created.
Procedure created.
Procedure created.
Procedure created.
PL/SQL procedure successfully completed.
PL/SQL procedure successfully completed.
COL1 COL2 COL3 COL4 COL5 COL6 COL7 COL8 COL9 COL10
12345 2829303132 234234 234234 234234
67890 2324252627 234234 234234 234234 332545
11121314 12345 234234 234234 234234 23432 32453245 345435 345435
151617 67890 234234 234234
1819202122 1112131415 234234 234234 234234 345435
2324252627
2829303132 234234 234234 234234 23432 32453245 345435 345435 4325435 345
7 rows selected.
Maybe you are looking for
-
Example: on the home page of the website http://www.dot.ri.gov there is an active link entitled "Overview of all Iway changes - Fall 2010" Clicking on it exposes the following url: http://www.dot.ri.gov/documents/iway/Iway_Changes_Fall2010.pdf Howeve
-
anyone have anything to say about these 750GB hard drives? they are pretty big, and i wonder how they are fairing in the a/v world. i have a couple of MacPro's from last year and want to fill up the storage bays. i'd like to get the 750's but.., let
-
How can I talk with more then one person at a time?
How can I talk with more then one person at a time? With Faxe time? Is thier software needed to do this or can it be done with the basic package?
-
Final Cut Pro to work on two computers simultaneously?
I have two iMac computers running the same version and serial number of Final Cut Pro. But, only one computer can work with Final Cut at a time. I have to log out from FCP to be able to open FCP on the second computer. This limits our ability to work
-
Can i use my mac as a screen for my pc?
can i use my mac as a screen for my pc?