Problem - insert JSON string into table in CLR function
Hi
I create a CLR function to insert JSON string into table.
With this line
mt = JsonConvert.DeserializeObject<MyTable>(jsonStr.ToString());
The class is OK (no error), but when I try to add the Assembly in Microsoft SQL Server Management Studio, it has error :
Assembly 'newtonsoft.json, version=4.5.0.0, culture=neutral, publickeytoken=30ad4fe6b2a6aeed.' was not found in the SQL catalog.
(I have Newtonsoft.Json in the Reference)
Please help !
Thanks
Hi Bob
Could you elaborate a bit more?
I think the code is ok. The problem is when I deploy the Visual Studio creates/alters the assembly, and get the error
Error: SQL72014: .Net SqlClient Data Provider: Msg 6503, Level 16, State 12, Line 1 Assembly 'newtonsoft.json, version=6.0.0.0, culture=neutral, publickeytoken=30ad4fe6b2a6aeed.' was not found in the SQL catalog.
ALTER ASSEMBLY [Database1]
FROM 0x4D5A90000300000004000000FFFF0000B800000000000000400000000000000000000000000000000000000000000000000000000000000000000000800000000E1FBA0E00B409CD21B8014CCD21546869732070726F6772616D2063616E6E6F742062652072756E20696E20444F53206D6F64652E0D0D0A2400000000000000504500004C0103000DE411540000000000000000E00002210B010B000012000000060000000000008E3000000020000000400000000000100020000000020000040000000000000006000000000000000080000000020000000000000300608500001000001000000000100000100000000000001000000000000000000000003C3000004F00000000400000A802000000000000000000000000000000000000006000000C000000042F00001C0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000080000000000000000000000082000004800000000000000000000002E7465787400000094100000002000000012000000020000000000000000000000000000200000602E72737263000000A8020000004000000004000000140000000000000000000000000000400000402E72656C6F6300000C0000000060000000020000001800000000000000000000000000004
An error occurred while the batch was being executed.
Done building project "Database1.sqlproj" -- FAILED.
This is my FillRow function. Without the bold line, the everything is fine. I can create the assembly, then create the SQL function. Done. When I call select from the SQL function, it returns 10 rows as expected.
public static IEnumerable getTable(SqlString jsonStr)
ArrayList resultCollection = new ArrayList();
MyTable mt;
//mt = JsonConvert.DeserializeObject<MyTable>(jsonStr.ToString());
int c = 1;
while (c < 10)
mt = new MyTable();
mt.GlobalId = c.ToString();
mt.DateSet = "DS=!=" + c.ToString();
mt.Timestamp = "TS==" + c.ToString();
mt.PartnerId = "PI==" + c.ToString();
mt.PartnerUserId = "PUI=" + c.ToString();
mt.UserIP = "UIP=" + c.ToString();
mt.UserAgent = "UG=" + c.ToString();
mt.Referer = "R=" + c.ToString();
resultCollection.Add(mt);
c++;
//resultCollection.Add(mt);
return resultCollection;
Similar Messages
-
Inserting XML String into Table with help of Stored Proc
I will be getting XML String from JAVA, which I have to insert in Table A, XML String is as follows
<?xml version = '1.0'?>
< TableA>
<mappings Record="3">
< MESSAGEID >1</ MESSAGEID >
< MESSAGE >This is available at your address!</ MESSAGE>
</mappings>
<mappings Record="3">
< MESSAGEID >2</ MESSAGEID>
< MESSAGE >This isn’t available at your address. </ MESSAGE>
</mappings>
</ TableA >
Table Structure*
MESSAGEID VARCHAR2(15 BYTE)
MESSAGE VARCHAR2(500 BYTE)
This is the stored procedure which I have written to insert data into TableA, V_MESSAGE will be input parameter for inserting XML String
create or replace procedure AP_DBI_PS_MESSAGE_INSERT
V_MESSAGE VARCHAR2(1024)
AS
declare
charString varchar2(80);
finalStr varchar2(4000) := null;
rowsp integer;
V_FILEHANDLE UTL_FILE.FILE_TYPE;
begin
-- the name of the table as specified in our DTD
xmlgen.setRowsetTag('TableA');
-- the name of the data set as specified in our DTD
xmlgen.setRowTag('mappings');
-- for getting the output on the screen
dbms_output.enable(1000000);
-- open the XML document in read only mode
v_FileHandle := utl_file.fopen(V_MESSAGE);
--v_FileHandle := V_MESSAGE;
loop
BEGIN
utl_file.get_line(v_FileHandle, charString);
exception
when no_data_found then
utl_file.fclose(v_FileHandle);
exit;
END;
dbms_output.put_line(charString);
if finalStr is not null then
finalStr := finalStr || charString;
else
finalStr := charString;
end if;
end loop;
-- for inserting the XML data into the table
rowsp := xmlgen.insertXML('ONE.TableA',finalStr);
dbms_output.put_line('INSERT DONE '||TO_CHAR(rowsp));
xmlgen.resetOptions;
end;Please Help
Edited by: 846857 on Jul 18, 2011 10:55 PMwith t as (select xmltype('<TableA >
<mappings Record="3">
<MessageId>1</MessageId>
<Message> This bundle is available at your address!</Message>
</mappings>
<mappings Record="3">
<MessageId>2</MessageId>
<Message>This isn’t available at your address. </Message>
</mappings>
</TableA >') col FROM dual)
--End Of sample data creation with subquery factoring.
--You can use the query from here with your table and column name.
select EXTRACTVALUE(X1.column_value,'/mappings/MessageId') MESSAGEID
,EXTRACTVALUE(X1.column_value,'/mappings/Message') MESSAGE
from t,table(XMLSEQUENCE(extract(t.COL,'/TableA/mappings'))) X1;Above Code works as i get result
MESSAGEID MESSAGE
1 This bundle is available at your address!
2 This isn’t available at your address.
_____________________________________________ now I want to insert the result into Table A... How to proceed... Please help
Edited by: 846857 on Jul 19, 2011 12:15 AM -
Can SQL*Loader Insert concatenated string into table
Hi All,
I want to insert a column, whose format is "abc" + to_char(sysdate,'YYYYMMDD'), into temp table. How can I do it? Thank you in advance.
Best Regards,
ShengHi Lukasz,
Thank you for your help! The "abc" is a constant string, it isn't a column. And I use concat function to solve the problem. like this
LOAD DATA
INFILE data.txt
INTO TABLE tmp_table
fields terminated by "," optionally enclosed by '"'
( c1 "concat('abc',TO_CHAR(SYSDATE, 'YYYYMMDD'))"
Sheng
Edited by: Sheng on 2013-5-26 下午4:44 -
Problem inserting xml doc into tables
I'm trying to load and xml doc into a table/columns using putXML. I clearly have elements in my xml doc that I do not want to load into the table. I am receiving the following error: The XML element tag 'VERB' does not match the name of any of the columns/attributes of the target database. I'm having difficulty figuring out how to exclude of ignore these elements.
Any help would be greatly appreciated.
Thanks,
JohnHi,
How about applying an XSL on the existing XML doc to create another XML doc to filter out the table column not found in the target db table, so that all the columns are matched and then use putXML to load?
Hope that helps.
OTN team@IDC -
Storing JSON string into Oracle table
Hi,
What is appropriate way to store JSON string into Oracle table?
Regards
PeterIf JSON becomes more popular, ORACLE might write data cartridge extension for JSONDB (in the same way as XMLDB).
Till then CLOB and NCLOB is your best choice, and leave the parsing in your application layer. -
How can i open a DOC or TXT file and insert the data into table?
How can i open a DOC or TXT file and insert the data into table?
I have a doc file . the doc include some columns and some rows.(for example 'ID,Name,Date,...').
I'd like open DOC file and I'd like insert them into the table with same columns.
Thanks.Use the SQL*Loader utility or the UTL_FILE package.
-
Problem inserting a gif into a blob field in a table with sqldev / forms6i
Problem solved - For those that might be interested, the errors don't make much sense - the problem was with the gif. Seems that these 28 gifs plus the new scans were saved from the scanner with
GIF - LZW, Transparent color: 255
Converting them to Black and white allowed them to be loaded.
If anyone understands why, I'd like to know
glenn
I was previously having a problem deleting a row with a blob and it was suggested that I create the table using rowdependencies - which I did as follows.
CREATE TABLE "MDD"."MDD_FIGURE2"
( "FG_FIGURENAME" VARCHAR2(18 BYTE),
"FG_FIGURE" BLOB,
CONSTRAINT "FG_FIGURENAME_NN" CHECK ("FG_FIGURENAME" IS NOT NULL) ENABLE
) ROWDEPENDENCIES;
Then I copied my data from my previous table with the following - and everything came across
INSERT INTO MDD_FIGURE2 (fg_figurename, fg_figure)
SELECT FIG_FIGNAME, FIG_FIGURE FROM MDD_FIGURE;
mdd_figure2 was then renamed to mdd_figure
The table, Mdd_Figure, already contains some 2000+ .gifs that were successfully loaded with Forms 6i (yes, I know it is old, but I am stuck with having to use it). All the .gifs I am loading are from scans and all are less than 64k. However, 28 .gifs would not load. When I insert the .gif into the field and committed the form, the status message tells me a record was written but when I check it, the blob is empty.
So, when I try to insert one of these problem .gifs in SqlDeveloper, I open the new mdd_figure table, select the blob field, open the edit dialog, set it to figure, select the .gif that I want to load and then save it. The blob field changes from NULL to BLOB, but it is empty. When I try to commit, I get the following error from SqlDev.
UPDATE "MDD"."MDD_FIGURE" SET WHERE ROWID = 'AAAOeWAAEAAABAlAAz' AND ORA_ROWSCN = '358136842'
One error saving changes to table "MDD"."MDD_FIGURE":
Row 14: ORA-01410: invalid ROWID
I use rollback to restore the record to it's previous state.
If I load one of the successfully loaded .gifs into the same field, it loads perfectly as follows.
UPDATE "MDD"."MDD_FIGURE" SET WHERE ROWID = 'AAAOeWAAEAAABAoAAp' AND ORA_ROWSCN = '358136522'
Commit Successful
It appears the 28 gifs have a problem. I've re-scanned them, with the same results. They are just small scanned line map images from our earlier publications. They view properly in several different graphics programs and I can't find anything wrong with them.
I notice that the ROWID's are different while the ORA_ROWSCN's are the same - but what is the significance of that?
Any suggestions as to what is happening and what I can do about it?
Thanks for any help you can give me.
glenn
(Database is 10R2 and sqldev is the most recent one)
Edited by: gconley on Sep 25, 2008 9:51 PMsolved it myself - problem was with the gif
-
Inserting long string into Oracle
When my code inserts about 5K character into a table, I got an error message saying that the Oracle could only handle 4K character. I am currently looking at LOB but havn't had a clear idea yet. Could someone give me some help on this? According to the sample code, I will have to use Oracle JDBC driver for LOB. But we are using BEA's Kona driver for all JDBC connections. Is there an easy way to insert long string?
hii
nams u solve ur problem using setCharacterStream method
but it does't work if the string more than 4000 char
raises "java.sql.SQLException: Protocol violation"
here's the code
PreparedStatement ps = con.prepareStatement( "UPDATE candidate SET cv_new = ?");
StringReader cvReader=new StringReader(cv_new);
int abc=cv_new.length();
ps.setCharacterStream( 1, cvReader, abc);
ps.executeUpdate();
is that any problem in that code or it's a jdbc driver broblem ??
i'm using classes 12.zip
thanks -
Sqlloader: how to insert -ve value into table
hi..
i had problem during loading. The error is Record 1: Rejected - Error on table FILE01, column AMOUNT.
ORA-01722: invalid number
For AMOUNT, the datatype is number(20,2).
here is my .ctl
LOAD DATA
INFILE 'file1bp0103.txt'
BADFILE 'file01.bad'
APPEND
INTO TABLE file01
acct_no POSITION(01:13),
amount POSITION(14:28),
description POSITION(29:32)
my .dat file
A500000030401- 32.74PYMT
A500000320106- 46.95PYMT
A500000520408- 63.95PYMT
A500000610301- 12.99PYMT
A500001720110- 56.21PYMT
A500001800103- 55.65PYMT
A500002000109- 27.25PYMT
A500002000305- 53.35PYMT
A500002080210- 75.04PYMT
A500002250106- 103.38PYMT
A500002500104- 60.69PYMT
A500002620902- 509.77PYMT
A500002621010- 398.69PYMT
what is the problem? is it because of my datatype?
please help me..
TQIs there a need to use dynamic sql here?
at the very least, try using bind variables instead of concatenating values like that.
EXECUTE IMMEDIATE 'insert into your_table (column_list) values (:val1, :val2, ...)'
USING l_val1, l_val2, l_val3 ... ; -
Using Cursor and FOR LOOP to INSERT the data into table
Hi all,
I have SELECT statement that returns 3 rows:
PROCESSNAME
PROTDATE
IMM
2013-12-18
Metrology
2013-11-18
CT
2013-12-04
SELECT processName, MAX(NVL(protStartDate, protCreateDate)) AS protDate
FROM TABLE(SEM_MATCH("{
?ipc rdf:type s:Protocol .
?ipc s:protocolNumber ?protNum .
?ipc s:protocolCreateDate ?protCreateDate .
OPTIONAL {?ipc s:protocolSchedStartDate ?protStartDate }
?ipra rdf:type s:ProcessAggregate .
?ipra s:hasProtocol ?iprot .
?iprot s:protocolNumber ?protNum .
?ipra s:processAggregateProcess ?processName.
}",sem_models("PROTS", "LINEARS"),NULL, SEM_ALIASES(SEM_ALIAS("","http://VISION/Data/SEMANTIC#"),SEM_ALIAS("s","http://VISION/DataSource/SEMANTIC#")),NULL))
Group by processName
Now I need to INSERT these values into the table along with the other values.
these other values come from different table.
INSERT INTO MODEL_CLASS_COUNTS (MODEL_NAME, CLASS_NAME, INS_COUNT, COUNT_DATETIME, PROCESS_NAME, PROT_DATE)
VALUES
("$MODEL",
"${i}",
(SELECT COUNT (DISTINCT S) FROM TABLE(SEM_MATCH(
"{?s rdf:type :${i} . }",SEM_Models("$MODEL"),NULL, SEM_ALIASES(SEM_ALIAS("","http://VISION/DataSource/SEMANTIC#")),NULL))),
SYSTIMESTAMP, %%here need to insert PROCESSNAME, PROTDATE%%
t was giving me error:
PL/SQL: ORA-22905: cannot access rows from a non-nested table item
so i enclosed sparql query into single quotes.
The code is as follows:
declare
type c_type is REF CURSOR;
cur c_type;
v_process varchar2(200);
v_pdate varchar2(200);
begin
open cur for
' SELECT processName, MAX(NVL(protStartDate, protCreateDate)) AS protDate <-- it's complaining about this being too long identifier, i think...
FROM TABLE
(SEM_MATCH (
?ipc rdf:type s:Protocol .
?ipc s:protocolNumber ?protNum .
?ipc s:protocolCreateDate ?protCreateDate .
OPTIONAL {?ipc s:protocolSchedStartDate ?protStartDate }
?ipra rdf:type s:ProcessAggregate .
?ipra s:hasProtocol ?iprot .
?iprot s:protocolNumber ?protNum .
?ipra s:processAggregateProcess ?processName.
}",SEM_Models("XCOMPASS", "XPROCESS"),NULL,
SEM_ALIASES(SEM_ALIAS("","http://VISION/Data/SEMANTIC#"),
SEM_ALIAS("s", "http://VISION/DataSource/SEMANTIC#")),NULL))
Group by processName';
loop
fetch cur into v_process, v_pdate;
exit when cur%NOTFOUND;
--here I need to insert v_process , v_pdate into my table along with other values...
dbms_output.put_line('values for process and prod_date are: ' || v_process || v_pdate );
end loop;
close cur;
end;
exit;
Now, I get an error:
ORA-00972: identifier is too long
Does anyone know way around this?Hi,
I tested something similar with insert into select and it worked fine :
insert into t_countries(ID,CITY ,POPULATION, DESCRIPTION, located, insdate )
SELECT 1 id, city, o , city||' is a nice city' description, max(nvl(locatedAt,'unknown')) as located,
SYSTIMESTAMP
FROM TABLE(SEM_MATCH(
'{GRAPH :gCH {<http://www.semwebtech.org/mondial/10/countries/CH/> :hasCity ?cityID .
?cityID :name ?city .
OPTIONAL{?cityID :locatedAt ?locatedAt .}
?cityID :population ?o .
SEM_Models('VIRT_MODEL_MONDIAL'),
SEM_Rulebases(null),
SEM_ALIASES(SEM_ALIAS('','http://www.semwebtech.org/mondial/10/meta#'),
SEM_ALIAS('prv','http://www.semwebtech.org/mondial/10/countries/CH/provinces/')
null))
group by city,o
order by city;
Or with execute immediate :
declare
v_country varchar2(200) :='http://www.semwebtech.org/mondial/10/countries/F/';
v_text varchar2(2000);
begin
v_text := 'insert into t_countries(ID,CITY ,POPULATION, DESCRIPTION, located, insdate )
SELECT 1 id, city, o , city||'' is a nice city'' description, max(nvl(locatedAt,''unknown'')) as located,
SYSTIMESTAMP
FROM TABLE(SEM_MATCH(
''{<'||v_country||'> :hasCity ?cityID .
?cityID :name ?city .
OPTIONAL{?cityID :locatedAt ?locatedAt .}
?cityID :population ?o .
SEM_Models(''VIRT_MODEL_MONDIAL''),
SEM_Rulebases(null),
SEM_ALIASES(SEM_ALIAS('''',''http://www.semwebtech.org/mondial/10/meta#'') ),
null))
group by city,o
order by city';
dbms_output.put_line(v_text);
delete from t_countries;
execute immediate v_text ;
commit;
end;
Marc -
Inserting blob image into table
ora.gif, image001.jpeg are the image names .these are stored in the location D:\oracle\Bfiles
create directory BFILE_FILES as ‘D:\oracle\Bfiles';
i want to insert the 2 images into table using blob
how to create the table and how to insert and how to test that image is inserted or notTom Kyte has it all Here
-
Insert query for insert all data into table in vb6 but it insert 1 row in table
This is My insert query in vb6 but it insert 1 row in table
But i want insert all data in the table which contain the id =1.
Note that billtabsuport is blank
i want solution for this
strSQL = " select * from billtabsuport1 where StockID=" & lblid.Caption
Set DBrecordset = DBConnection.Execute(strSQL)
strSQL = " Insert into billtabsuport values('" & DBrecordset("StockID") & "','" & DBrecordset("C_Name") & "','" & DBrecordset("C_Add") & "','" & DBrecordset("C_Mobile") & "','" & DBrecordset("Invoice_No") & "','" & DBrecordset("Date") & "','" & DBrecordset("Order_No") & "','" & DBrecordset("T_Name") & "','" & DBrecordset("Dest") & "','" & DBrecordset("D_Date") & "','" & DBrecordset("Tyres_Serial_No") & "','" & DBrecordset("P_Desc") & "','" & DBrecordset("PR") & "','" & DBrecordset("Branded_NonBranded") & "','" & DBrecordset("Claim_No") & "','" & DBrecordset("Qty") & "','" & DBrecordset("U_Price") & "','" & DBrecordset("I_Value") & "','" & DBrecordset("V_Rate") & "','" & DBrecordset("V_Amt") & "','" & DBrecordset("Size") & "','" & DBrecordset("Pattern") & "','" & DBrecordset("TypesOfStock") & "','" & DBrecordset("TypesOfTube_Flap") & "','" & DBrecordset("VatAmount") & "')"
DBConnection.Execute (strSQL)The syntax for inserting from one set of tables to a new table is:
insert into newtable
(field1, field2, etc)
select somefield1, somefield2, etc
from some other tables
where whatever -
Problem to upload excel into table using sqlldr
hi ,
i'm using following code on 10g forms (when button pressed) to upload excel to oracle table i.e.
--V_USERID_CS:=USER||'/'||PWD||'@'||CONNSTR ;
V_USERID_CS:='saf_integ'||'/'||'saf_integ'||'@'||'ORCLREG'; ---connection string for AS on this machine, control files and .csv files are also on that machine--
LOG_EVENTS('BEFORE HOST CALLING'); just to trace the message
LOG_EVENTS('SQLLDR'||' '||RTRIM(V_USERID_CS)||' '||'control='||'c:\overtime.ctl'||' '||'log='||'C:\LOG_FILE.log'||';'); just to trace the command
HOST('SQLLDR'||' '||RTRIM(V_USERID_CS)||' '||'control='||'c:\overtime.ctl'||' '||'log='||'C:\LOG_FILE.log'||';');
LOG_EVENTS('AFTER HOST CALLING'); just to trace the message
COMMIT;
LOG_EVENTS IS PROCEDURE TO TRACE THE BUG; WHICH SHOWS THE DATA AS GIVEN BELOW:
SYSDATE_1 ERROR_TEXT ID
5/14/2010 BEFORE HOST CALLING 8464274
5/14/2010 SQLLDR saf_integ/saf_integ@ORCLREG control=c:\overtime.ctl log=C:\LOG_FILE.log; 8464275
5/14/2010 AFTER HOST CALLING 8464276
i'm not getting any error but even data is not uploaded into table.
but when i get the same command from the log table run directly on that machine it's working fine.
please suggest me where is the gap?
Thanks
kami'm not getting any error but even data is not uploaded into table.
but when i get the same command from the log table run directly on that machine it's working fine.
please suggest me where is the gap?The SQLLDR.EXE file exists where. In the APPLICATION SERVER or in the CLIENT MACHINE. If it is in the client machine. Then you need to use CLIENT_HOST instead of HOST. CLIENT_HOST exists in webutil library.
-Ammad -
How to insert data with & into table..
Hi,
i want to insert following data to table
sql>insert into emp values('company & co');
Enter value for co:
how to avoid this ?You should disable the interactive prompt in SQL Plus. How to do check this link
http://www.orafaq.com/wiki/SQL*Plus_FAQ#How_does_one_disable_interactive_prompting_in_SQL.2APlus.3F -
Inserting the Comma Separated Strings into Table
Hi Seniors,
i had two string and i want to insert the records in the Table COMMENT . In this way.
would u please give some programe to insert the records.
The Data and the Table
( 901,902,903,904 )
( 'hai','nice','good & mail is [email protected] ','excellent and the phone 011-235323' )
comm_id loc_id company_name comments
1 10 901 Hai
2 10 902 nice
3 10 903 good & mail is [email protected]
4 10 904 excellent and the phone 011-235323
Thanks
SeenuHi, Seenu,
In Oracle 10 (and up) you can easily split a comma-delimited list using REGEXP_SUBSTR.
INSTR and SUBSTR can do the same thing in any version, but it's more complicated.
See the general instructions below:
/* How to Split a Delimited String
This shows how to take a single row with a delimited string, such as
Animal amoeba,bat,cedusa,dodo
and transform it into multiple rows:
Animal 1 amoeba
Animal 2 bat
Animal 3 cedusa
Animal 4 dodo
PROMPT ========== -1. sep_char parameter ==========
VARIABLE sep_char VARCHAR2 (10)
EXECUTE :sep_char := ',';
SELECT :sep_char AS sep_char
FROM dual;
PROMPT ========== 0. string_test table ==========
DROP TABLE string_test;
CREATE TABLE string_test
( grp_name VARCHAR2 (10)
, list_txt VARCHAR2 (50)
INSERT INTO string_test (grp_name, list_txt) VALUES ('Animal', 'amoeba,bat,cedusa,dodo');
INSERT INTO string_test (grp_name, list_txt) VALUES ('Date', '15-Oct-1582,16-Oct-2008');
INSERT INTO string_test (grp_name, list_txt) VALUES ('Nothing', NULL);
INSERT INTO string_test (grp_name, list_txt) VALUES ('Place', 'New York');
INSERT INTO string_test (grp_name, list_txt) VALUES ('Skip', 'Hop,,Jump');
SELECT *
FROM string_test
ORDER BY grp_name;
PROMPT ========== Q1. Oracle 11 Query ==========
WITH cntr AS -- Requires Oracle 9
( -- Begin sub-query cntr, to generate n (1, 2, 3, ...)
SELECT LEVEL AS n -- Requires Oracle 9
FROM dual
CONNECT BY LEVEL <= 1 + (
SELECT MAX ( REGEXP_COUNT (list_txt, :sep_char) ) -- Requires Oracle 11
FROM string_test
) -- End sub-query cntr, to generate n (1, 2, 3, ...)
SELECT grp_name
, n
, REGEXP_SUBSTR ( list_txt -- Requires Oracle 10
, '[^' || :sep_char || ']' -- Anything except sep_char ...
|| '+' -- ... one or more times
, 1
, n
) AS item_txt
FROM string_test
JOIN cntr -- Requires Oracle 9
ON n <= 1 + REGEXP_COUNT (list_txt, :sep_char) -- Requires Oracle 11
ORDER BY grp_name
, n;
/* Notes:
REGEXP_SUBSTR (s, '[^,]+', 1, n)
returns the n-th item in a comma-delimited list s.
If there are fewer than n items, it returns NULL.
One or more consecutive characters other than comma make an item, so
'Hop,,Jump' has two items, the second one being 'Jump'.
The sub-query cntr produces a list of integers 1, 2, 3, ..., w
where w is the worst-case (the largest number of items in any list).
This actually counts separators, not items, (e.g., it counts both
commas in 'Hop,,Jump', even though), so the w it produces may be
larger than is really necessary. No real harm is done.
PROMPT ========== Q2. Possible Problems Fixed ==========
WITH cntr AS
( -- Begin sub-query cntr, to generate n (1, 2, 3, ...)
SELECT LEVEL AS n
FROM dual
CONNECT BY LEVEL <= 1 + (
SELECT MAX ( REGEXP_COUNT (list_txt, :sep_char) )
FROM string_test
) -- End sub-query cntr, to generate n (1, 2, 3, ...)
SELECT grp_name
, n
, REGEXP_SUBSTR ( list_txt
, '[^' || :sep_char || ']' -- Anything except sep_char ...
|| '+' -- ... one or more times
, 1
, n
) AS item_txt
FROM string_test
JOIN cntr ON n <= 1 + NVL ( REGEXP_COUNT (list_txt, :sep_char) -- Problem (1)
, 0
WHERE REGEXP_SUBSTR ( list_txt -- Problem (2)
, '[^' || :sep_char || ']' -- Anything except sep_char ...
|| '+' -- ... one or more times
, 1
, n
) IS NOT NULL
OR list_txt IS NULL -- Problems (1) and (2) together
ORDER BY grp_name
, n;
(Possible) Problems and Fixes
(1) If list_txt IS NULL, then REGEXP_COUNT (list_txt, :sep_char)
returns NULL, the join condition fails, and the output
contains nothing corresponding to the row from string_test.
If you want a NULL item to appear in the results, use
NVL to make sure the expression returns 0 instead of NULL.
(2) If list_txt contains multiple consecutive sep_chars (or if it
begins or ends with sep_char, then the original query
will return NULL items. To suppress these, add a WHERE
clause to test that the item_txt to be displayed IS NOT NULL.
PROMPT ========== Q3. Oracle 8.1 Query ===========
SELECT grp_name
, n
, SUBSTR ( list_txt
, begin_pos
, end_pos - begin_pos
) AS item_txt
FROM ( -- Begin sub-query to compute begin_pos and end_pos
SELECT grp_name
, n
, list_txt
, INSTR ( :sep_char || list_txt
, :sep_char
, 1
, n
) AS begin_pos
, INSTR ( list_txt || :sep_char
, :sep_char
, 1
, n
) AS end_pos
FROM string_test
, ( -- Begin sub-query cntr, to generate n (1, 2, 3, ...)
SELECT ROWNUM AS n
FROM all_objects
WHERE ROWNUM <= 1 + (
SELECT MAX ( LENGTH (list_txt)
- LENGTH (REPLACE (list_txt, :sep_char))
FROM string_test
) -- End sub-query cntr, to generate n (1, 2, 3, ...)
cntr
WHERE n <= 1 + ( LENGTH (list_txt)
- LENGTH (REPLACE (list_txt, :sep_char))
) -- End sub-query to compute begin_pos and end_pos
ORDER BY grp_name
, n;
/* Version-Dependent Features and Work-Arounds
The code above, Q3, runs in Oracle 8.1.
The following changes were made to Q1:
(11) REGEXP_COUNT was introduced in Oracle 11.
In earlier versions, to find the number of sep_chars in list_txt,
see how much the LENGTH changes when sep_chars are removed.
(10) REGEXP_SUBSTR was introduced in Oracle 10.
In earlier versions, use INSTR to find where the sep_chars are,
and use SUBSTR to get the sub-strings between them.
(Using this technique, 'Hop,,Jump' still contains three items,
but now item 2 IS NULL and item 3 is 'Jump'.)
(9.a) The WITH-clause was introduced in Oracle 9
In earlier versions, use in-line views.
(9.b) "CONNECT BY LEVEL < constant" doesn't work in Oracle 8.
Use ROWNUM from any sufficiently large table or view instead.
(9.c) ANSII join notation (JOIN table_name ON ...) was introduced in Oracle 9
In earlier versions, join condition go in a WHERE-clause.
*/
Maybe you are looking for
-
Backup Failure after Mountain Lion
After I upgraded to Mountain Lion I got an error every time I tried to backup over wireless. I figured I would just backup from scratch, therefore I connected the hard drive to my USB, deleted the sparsbundle and then connected the hard drive back up
-
Mini to iMac ram compatible?
Hello! So long story short, I purchased a mini and some ram and had to return the mini and couldn't get it replaced (they were out of them), so i upgraded to an iMac. I'm wanting to return the ram i bought for the mini but If i could slap it in the i
-
PSE 7: "Base directory" for locating files?
I'm trying to salvage a Photoshop Elements 7 catalog that won't cleanly regenerate thumbtails on the old machine (so it hangs). I tried deleting the cache, but the system crashes the first couple of times regenerating the thumbnails, and eventually s
-
Deployed Android project using Flash Builder Burrito not working on mobiles
Hi, I have created a simple "Hello World" Application using Flash Builder Burrito SDK. I have tested the result in the emulator it is working great. After that i deployed the application using "Export Release Build Option" and entered valid certifica
-
Combined PDFs have bigger jpegs then word doc
I am having an issue with adobe 11. If I open a word doc and print to my pdf printer the pdf created looks identical to the word 13 doc. If I open adobe and choose to combine files all the graphics in the combined pdf are a little bit bigger then the