Oracle Regex Replace on String Query - sql

Query to fetches the sub xml from an xml saved in the CLOB column of my table is given as :
select REGEXP_REPLACE(xmltype(t.prov_request).extract('//SOAP_Domain_Msg/Body').getStringVal(),'<Body>|</Body>','') xml
from tbl_prov_comptel
There is "SO1_USERNAME" value="xxx" in the string returned by the above query.
What i want to achieve is to form a consolidated query and append something in the start of the expression above.
ie."SO1_USERNAME" value="qwexxx"

Oracle Setup:
CREATE TABLE tbl_prov_comptl ( prov_request CLOB );
INSERT INTO tbl_prov_comptl VALUES (
'<SOAP_Domain_Msg><Body><NS4:ModifyRequest xmlns:NS4="http://soa.comptel.com/2011/02/instantlink"><NS4:RequestParameters> <NS4:Parameter name="SO1_USERNAME" value="222671150"/></NS4:RequestParameters> </NS4:ModifyRequest></Body></SOAP_Domain_Msg>'
);
Query:
SELECT EXTRACTVALUE(
xml,
'//NS4:ModifyRequest/NS4:RequestParameters/NS4:Parameter[name="SO1_USERNAME"]/#value',
'xmlns:NS4="http://soa.comptel.com/2011/02/instantlink"'
) AS SO1_USERNAME,
x.xml.getStringVal() AS xml
FROM (
SELECT XMLType( prov_request ).extract( '//SOAP_Domain_Msg/Body/*' ) AS xml
FROM tbl_prov_comptl
) x;
Output:
SO1_USERNAME XML
------------ ------------------------------------------------------------------------------
222671150 <NS4:ModifyRequest xmlns:NS4="http://soa.comptel.com/2011/02/instantlink"><NS4
:RequestParameters> <NS4:Parameter name="SO1_USERNAME" value="222671150"/></NS
4:RequestParameters> </NS4:ModifyRequest>

Related

SQL Parse xml column data

I have very little experience with SQL Server. Here is what I am trying to accomplish:
I have a table with many rows. Every row contains a column named "Config". The data stored in the Config column is of the xml type. The xml structure looks like this:
<root>
<path1>
<path2>
<path3>true</path3>
</path2>
</path1>
</root>
I am trying to go through every row in the table and find the percentage of true to false values of <path3>.
I looked at some SQL documentation and tried to use the value() function I am having difficulties extracting the XML data from the column:
select Config.value('(/root/path1/path2/path3)[1]','nvarchar(max)') from [MyDB].[dbo].[MyTable]
Here is the result of my query:
I would like to query and extract data from the XML "Config" column of my table and aggregate that data into columns.
You need to specify namespaces in the query when xml is built with namespaces. For example
CREATE TABLE tbl (Config xml);
INSERT INTO tbl (Config)
VALUES ('<root xmlns="abc">
<path1>
<path2>
<path3>true</path3>
</path2>
</path1>
</root>') ;
Then
with xmlnamespaces (DEFAULT 'abc')
select Config.value('(/root/path1/path2/path3)[1]','nvarchar(max)') path3Txt
from tbl;
or explicit specification
with xmlnamespaces ('abc' as x)
select Config.value('(/x:root/x:path1/x:path2/x:path3)[1]','nvarchar(max)') path3Txt
from tbl;
You would need to use CROSS APPLY. Check it out.
SQL
-- DDL and sample data population, start
DECLARE #tbl TABLE (ID INT IDENTITY(1,1) PRIMARY KEY, [Config] XML);
INSERT INTO #tbl
VALUES (N'<root>
<path1>
<path2>
<path3>true</path3>
</path2>
</path1>
</root>')
, (N'<root>
<path1>
<path2>
<path3>false</path3>
</path2>
</path1>
</root>');
-- DDL and sample data population, end
;WITH rs AS
(
SELECT ID
, col.value('(./text())[1]','VARCHAR(20)') AS Result
FROM #tbl tbl
CROSS APPLY tbl.[Config].nodes('/root/path1/path2/path3') AS tab(col)
)
SELECT * FROM rs;

How to Select SQL for XML with fixed head line

I have a simple SQL table with Values "Alpha", "Bravo" and "Charlie".
I Need to get result as displayed. The data within transaction: type, date, etc. are static and should be part of the select Statement.
I think this can be done using
SELECT ... for XML
But don't know how?
CREATE TABLE [dbo].[SampleTable]([ID_extern] [varchar](50) NULL)
INSERT INTO SampleTable VALUES ('Alpha')
INSERT INTO SampleTable VALUES ('Bravo')
INSERT INTO SampleTable VALUES ('Charlie')
INSERT INTO SampleTable VALUES ('Delta')
Here is a little kick-start for you
Example
Select [transaction/#type]='import_serial_number'
,[transaction/#date]='123459'
,[transaction/#vaultname]='Type in the name of the vault here'
,[transaction/serial_number/#name] = 'SampleAppendSerialNo'
,[transaction/serial_number/#mode] = 'append'
,[transaction/serial_number] = (
Select [serno_item/#item_counter] = row_number() over (order by ID_extern)
,[serno_item/#serno_item] = ID_extern
From SampleTable
For XML Path (''),TYPE
)
For XML Path('transactions'),Root('xml')
Returns
<xml>
<transactions>
<transaction type="import_serial_number" date="123459" vaultname="Type in the name of the vault here">
<serial_number name="SampleAppendSerialNo" mode="append">
<serno_item item_counter="1" serno_item="Alpha" />
<serno_item item_counter="2" serno_item="Bravo" />
<serno_item item_counter="3" serno_item="Charlie" />
<serno_item item_counter="4" serno_item="Delta" />
</serial_number>
</transaction>
</transactions>
</xml>
Where a column value goes in the XML is determined by a path in an alias. Use # for attributes. To get the ordinals you can use row_number().
Something like
SELECT row_number() OVER (ORDER BY id_extern) "serno_item/#item_counter",
id_extern "serno_item/#item_value"
FROM simple
FOR XML PATH ('');
gives you the inner part of the XML. You can either try nested queries or use string concatenation (concat()) to prepend/append the outer parts like in the following.
SELECT convert(xml, concat('<serial_number type="">',
(SELECT row_number() OVER (ORDER BY id_extern) "serno_item/#item_counter",
id_extern "serno_item/#item_value"
FROM simple
FOR XML PATH ('')),
'</serial_number>'));
(I'm not going to type all that stuff off of your screen shot, so this is just exemplary.)

SQL Server 2012 create list of VARBINARY in single XML element

I am currently struggling to find a solution to the following problem.
I have a result set of VARBINARY values - for example:
QAAAAAAAAAE=
QAAAAAAAAAQ=
these results Need to be packed into a XML Element delimited by a single space (to siginify an array of values). Example of how the result should look:
<results>QAAAAAAAAAE= QAAAAAAAAAQ=</results>
The issue I am having while using XML PATH is that I cannot combine a ' ' (varchar) and the result varbinary field. If I add the ' ' before the result and then convert to varbinary the result is incorrect due to having converted the space as well. Here is an example of what I have attempted thus far:
(
STUFF((SELECT DISTINCT ' ' + CONVERT( VARBINARY, id)
FROM results
FOR XML PATH('ns2:children')
),1,1,'')
),
You should not deal with XML on string level. This might have various side effects...
You can try this:
I fill a table with some values in a VARBINARY column:
DECLARE #table TABLE(SomeData VARBINARY(MAX));
INSERT INTO #table VALUES(0x12AF)
,(CAST('test' AS VARBINARY(MAX)))
,(CAST(GETDATE() AS VARBINARY(MAX)));
SELECT *
FROM #table;
The result
SomeData
0x12AF
0x74657374
0x0000A81100AD9F69
If you get this as XML, the conversion to base64 is done implicitly
SELECT * FROM #table FOR XML PATH('result')
the result
<result>
<SomeData>Eq8=</SomeData>
</result>
<result>
<SomeData>dGVzdA==</SomeData>
</result>
<result>
<SomeData>AACoEQCtn2k=</SomeData>
</result>
Now there is XQuery-function data() to your rescue. It will automatically concatenate all sub-values separated by a blank:
SELECT(
SELECT *
FROM #table
FOR XML PATH('result'),TYPE
).query('data(/result/SomeData)') AS result
FOR XML PATH('results')
The result is
<results>
<result>Eq8= dGVzdA== AACoEQCtn2k=</result>
</results>
Pls. try short of SQL Command which could help u to achieve the above result :
SELECT REPLACE(T.Data, '</results><results>', ' ')
FROM
(
SELECT STUFF(
(
SELECT DATA [results]
FROM <table_name> FOR XML PATH('')
), 1, 1, '<') [Data]
) T;
Result :
<results>QAAAAAAAAAE= QAAAAAAAAAQ=</results>
If I understand what do you want?! A way to get <results>QAAAAAAAAAE= QAAAAAAAAAQ=</results> as result is:
select ltrim((
select ' '+cast(id as varchar(50))
from t
group by id
for xml path(''))) results
for xml path('');
SQL Fiddle Demo

ORACLE SQL: How can I get the XML elements from within a column of XMLTYPE

I have an multiple xml documents which look like this:
<farm>
<name>Johns Farm</name>
<size>50 hectares</size>
<employees>20</employees>
<fruits>
<fruit>Banana</fruit>
<fruit>Apple</fruit>
<fruit>Watermelon</fruit>
</fruits>
</farm>
I have got this in an oracle database like this:
CREATE TABLE FARM_XML_TABLE
(FARM_NUMBER NUMBER NOT NULL PRIMARY KEY, FARM_XML XMLTYPE NOT NULL)
XMLTYPE COLUMN FARM_XML STORE AS BINARY XML
XMLSCHEMA
"http://myproject.com/farmschema.xsd"
ELEMENT "farm";
The various farms are stored in the FARM_XML column. There is about 5 of them
How can I retrieve only the name and employee elements from the FARM_XML column of multiple farms in the form of an XML. I want the output to be like this:
<farm>
<name>Johns Farm</name>
<employees>20</employees>
</farm>
<farm>
<name>Harrys Farm</name>
<employees>10</employees>
</farm>
I have tried doing this, but the output isn't all the xml elements that I want.
SELECT extract(FARM_XML, 'farm/name').getStringVal()
FROM FARM_XML_TABLE;
Oracle Setup:
CREATE TABLE FARM_XML_TABLE(
FARM_NUMBER NUMBER PRIMARY KEY,
FARM_XML XMLTYPE NOT NULL
)
XMLTYPE COLUMN FARM_XML STORE AS BINARY XML;
INSERT INTO FARM_XML_TABLE VALUES(
1,
XMLtype( '<farm>
<name>Johns Farm</name>
<size>50 hectares</size>
<employees>20</employees>
<fruits>
<fruit>Banana</fruit>
<fruit>Apple</fruit>
<fruit>Watermelon</fruit>
</fruits>
</farm>' )
);
Query 1 - Rebuild the XML:
SELECT FARM_NUMBER,
XMLElement(
"farm",
XMLElement( "name", EXTRACTVALUE( farm_xml, '/farm/name' ) ),
XMLElement( "employees", EXTRACTVALUE( farm_xml, '/farm/employees' ) )
) AS xml
FROM FARM_XML_TABLE;
or (updated - simpler version):
SELECT FARM_NUMBER,
XMLElement(
"farm",
EXTRACT( farm_xml, '/farm/name' ),
EXTRACT( farm_xml, '/farm/employees' )
) AS xml
FROM FARM_XML_TABLE;
Query 2 - Delete non-matching elements from the existing XML:
SELECT FARM_NUMBER,
DELETEXML(
farm_xml,
'/farm/*[name()!=''name''][name()!=''employees'']'
) AS xml
FROM FARM_XML_TABLE;
Output:
(Both output the same)
FARM_NUMBER XML
----------- -------------------------------------------------------------
1 <farm><name>Johns Farm</name><employees>20</employees></farm>

Query xml using extract over CLOB column in Oracle

We are storing the xml in oracle database. The column type is CLOB.
I could fetch data from the xml tag with below query. When i execute the query i am getting null.
XML in the column:
<input xmlns="http://google.com/testsystem"
xmlns:testsystem="http://test.com/testSystem"
xmlns:tns="http://google.com/testService/">
<ProcessData>
<reviewYear>2014-2015</reviewYear>
</ProcessData>
</input>
Table name : test_table
Column name : input_xml
Column type : CLOB
Query:
select extract(xmltype(input_xml),'//reviewYear/text()').getStringVal() as data
from test_table
where id = 1;
Result:
DATA
------------------------------------
you need to specify namespace, please, try next query
select extract(xmltype('<input xmlns="http://google.com/testsystem"
xmlns:testsystem="http://test.com/testSystem"
xmlns:tns="http://google.com/testService/">
<ProcessData>
<reviewYear>2014-2015</reviewYear>
</ProcessData>
</input>'),'/input/ProcessData/reviewYear/text()', 'xmlns="http://google.com/testsystem" xmlns:testsystem="http://test.com/testSystem" xmlns:tns="http://google.com/testService/"').getStringVal() as data
from dual
UPD.
for update try
select updatexml(xmltype('<input xmlns="http://google.com/testsystem"
xmlns:testsystem="http://test.com/testSystem"
xmlns:tns="http://google.com/testService/">
<ProcessData>
<reviewYear>2014-2015</reviewYear>
</ProcessData>
</input>'), '/input/ProcessData/reviewYear/text()', '2013-2014',
'xmlns="http://google.com/testsystem" xmlns:testsystem="http://test.com/testSystem" xmlns:tns="http://google.com/testService/"').getclobval() as data
from dual