I've got table in mssql, and one column of it contains XML. Most of XML in this column looks like this:
<AuthenticationParams xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<MyParams>
<Username>AmaryllisAPITest</Username>
<ApplicationId>3</ApplicationId>
</MyParams>
<AlsoParams>
<AuthBehavior>Authorization</AuthBehavior>
<SecretKey>MVHXAQA5kF4Ab9siV4vPA4aVPn1EKhbqIBrpCZx2Hg</SecretKey>
</AlsoParams>
</AuthenticationParams>
I want to relocate AuthBehavior node right after AuthenticationParams node, so it will look like this:
<AuthenticationParams xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<AuthBehavior>Authorization</AuthBehavior>
<MyParams>
<Username>AmaryllisAPITest</Username>
<ApplicationId>3</ApplicationId>
</MyParams>
<AlsoParams>
<SecretKey>MVHXAQA5kF4Ab9siV4vPA4aVPn1EKhbqIBrpCZx2Hg</SecretKey>
</AlsoParams>
</AuthenticationParams>
How can I do that? Thanks for any help.
Try this code:
DECLARE #xml xml = '<AuthenticationParams xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<MyParams>
<Username>AmaryllisAPITest</Username>
<ApplicationId>3</ApplicationId>
</MyParams>
<AlsoParams>
<AuthBehavior>Authorization</AuthBehavior>
<SecretKey>MVHXAQA5kF4Ab9siV4vPA4aVPn1EKhbqIBrpCZx2Hg</SecretKey>
</AlsoParams>
</AuthenticationParams>';
DECLARE #temp TABLE (XmlData xml);
INSERT #temp VALUES (#xml);
UPDATE t
SET XmlData.modify('insert /AuthenticationParams/AlsoParams/AuthBehavior
as first
into (/AuthenticationParams)[1]')
FROM #temp t;
UPDATE t
SET XmlData.modify('delete /AuthenticationParams/AlsoParams/AuthBehavior')
FROM #temp t;
SELECT * FROM #temp;
Related
I try to rename element <Visible> to <IsVisible>, but this SELECT returns element Visible without child elements, how can I get Visible with UserId and RoleId elements?
DECLARE #xml XML =
N'<Root xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<FieldId>2200</FieldId>
<Visible xsi:type="UserRole">
<UserId xsi:type="CurrentUserId" />
<RoleId>26</RoleId>
</Visible>
</Root>';
SELECT #xml.query(N'let $nd:=(//*[local-name()="Visible"])[1]
return
<IsVisible> {$nd/#*}
{$nd/text()}
</IsVisible>
')
Try this.
DECLARE #xml XML =
N'<Root xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<FieldId>2200</FieldId>
<Visible xsi:type="UserRole">
<UserId xsi:type="CurrentUserId" />
<RoleId>26</RoleId>
</Visible>
</Root>';
SELECT #xml.query(N'let $nd:=(//*[local-name()="Visible"])[1]
return
<IsVisible> {$nd/#*}
{$nd/*}
</IsVisible>
')
You can either use XQuery (FLWOR) or a simple replace
DECLARE #xml XML =
N'<Root xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<FieldId>2200</FieldId>
<Visible xsi:type="UserRole">
<UserId xsi:type="CurrentUserId" />
<RoleId>26</RoleId>
</Visible>
</Root>';
--Works, but will reorganise your namespace declarations
WITH XMLNAMESPACES('http://www.w3.org/2001/XMLSchema' AS xsd
,'http://www.w3.org/2001/XMLSchema-instance' AS xsi)
SELECT #xml.query(N'<Root>
{
for $nd in /Root/*
return
if(local-name($nd)!="Visible") then
$nd
else
<IsVisible>{$nd/#*}
{$nd/*}
</IsVisible>
}
</Root>
');
--Might be easier here
SELECT CAST(
REPLACE(REPLACE(
CAST(#xml AS NVARCHAR(MAX))
,'<Visible ','<IsVisible ')
,'</Visible>','</IsVisible>')
AS XML)
I have this structure in my sql server :
<?xml version="1.0" encoding="utf-16"?>
<HydroResultTestParameterView xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ReceptionId>11</ReceptionId>
<CapsuleCompany>BR</CapsuleCompany>
<CapsuleSerialNumber>228154</CapsuleSerialNumber>
<CapsuleType>1</CapsuleType>
<CapsuleBuiltDate>1389</CapsuleBuiltDate>
<CapsuleExpireDate>1405</CapsuleExpireDate>
<GasSystemGeneration>1</GasSystemGeneration>
<Remark>ok</Remark>
</HydroResultTestParameterView>
My datatype of my column in nvarchar(max).So i want to get all of ReceptionId result that has CapsuleCompany=BR .How can i find these result ?
This explicitely selects all nodes using a XPath expression, taking all HydroResultTestParameterView with a sub-element CapsuleCompany with text = "BR": /HydroResultTestParameterView[CapsuleCompany="BR"]/ReceptionId
DECLARE #t TABLE(x XML);
INSERT INTO #t(x)VALUES(N'<HydroResultTestParameterView xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ReceptionId>11</ReceptionId>
<CapsuleCompany>BR</CapsuleCompany>
<CapsuleSerialNumber>228154</CapsuleSerialNumber>
<CapsuleType>1</CapsuleType>
<CapsuleBuiltDate>1389</CapsuleBuiltDate>
<CapsuleExpireDate>1405</CapsuleExpireDate>
<GasSystemGeneration>1</GasSystemGeneration>
<Remark>ok</Remark>
</HydroResultTestParameterView>');
SELECT
n.v.value('.[1]','NVARCHAR(MAX)')
FROM
#t
CROSS APPLY x.nodes('/HydroResultTestParameterView[CapsuleCompany="BR"]/ReceptionId') AS n(v)
SELECT
convert(xml,ResultTest).query('/HydroResultTestParameterView/CapsuleSerialNumber')
FROM
[S].[dbo].[HydrostaticTests]
WHERE
convert(xml,ResultTest).exist('/HydroResultTestParameterView[CapsuleSerialNumber="47274"]') = 1;
//-----------------
SELECT
convert(xml,ResultTest).value('(/HydroResultTestParameterView/CapsuleSerialNumber)[1]', 'int')
FROM
[S].[dbo].[HydrostaticTests]
WHERE
convert(xml,ResultTest).exist('/HydroResultTestParameterView[CapsuleSerialNumber="47274"]') = 1;
I have a XML like below. In this i want to fetch 'Name' value. i.e AAA in SQL Server.
<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:out="http://www.google.com">
<soapenv:Body>
<MER xmlns="http://www.google.com/services">
<ns1:RequestHeader xmlns:ns1="http://www.google.com//services">
<ns1:Info>
<ns1:Name>AAA</ns1:Name>
<ns1:TransactionId>Mdow0-NHPHuNu7eiEUxb</ns1:TransactionId>
<ns1:SubmitDateTime>2015-09-12T15:48:44.000Z</ns1:SubmitDateTime>
<ns1:SessionId>Mdow0-NHPHuNu7eiEUxb</ns1:SessionId>
<ns1:Timeout>60</ns1:Timeout>
<ns1:MaxRows>100</ns1:MaxRows>
<ns1:TransactionLog>
<ns1:Info1>1234567</ns1:Info1>
<ns1:Info2>ABC123</ns1:Info2>
</ns1:TransactionLog>
</ns1:Info>
<ns1:CorrelatedData>
<ns1:UserID>ABC123</ns1:UserID>
<ns1:UserRole>My Members</ns1:UserRole>
<ns1:TransactionName>Login</ns1:TransactionName>
<ns1:ClientSubmitDateTime>2010-09-12 11:48:44 PM</ns1:ClientSubmitDateTime>
</ns1:CorrelatedData>
</ns1:RequestHeader>
<SearchCriteria>
<MemberID>123456</MemberID>
</SearchCriteria>
</MER>
SqlFiddleDemo
DECLARE #x XML =
N'<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:out="http://www.google.com">
<soapenv:Body>
<MER xmlns="http://www.google.com/services">
<ns1:RequestHeader xmlns:ns1="http://www.google.com//services">
<ns1:Info>
<ns1:Name>AAA</ns1:Name>
<ns1:TransactionId>Mdow0-NHPHuNu7eiEUxb</ns1:TransactionId>
<ns1:SubmitDateTime>2015-09-12T15:48:44.000Z</ns1:SubmitDateTime>
<ns1:SessionId>Mdow0-NHPHuNu7eiEUxb</ns1:SessionId>
<ns1:Timeout>60</ns1:Timeout>
<ns1:MaxRows>100</ns1:MaxRows>
<ns1:TransactionLog>
<ns1:Info1>1234567</ns1:Info1>
<ns1:Info2>ABC123</ns1:Info2>
</ns1:TransactionLog>
</ns1:Info>
<ns1:CorrelatedData>
<ns1:UserID>ABC123</ns1:UserID>
<ns1:UserRole>My Members</ns1:UserRole>
<ns1:TransactionName>Login</ns1:TransactionName>
<ns1:ClientSubmitDateTime>2010-09-12 11:48:44 PM</ns1:ClientSubmitDateTime>
</ns1:CorrelatedData>
</ns1:RequestHeader>
<SearchCriteria>
<MemberID>123456</MemberID>
</SearchCriteria>
</MER>
</soapenv:Body>
</soapenv:Envelope>';
WITH XMLNAMESPACES(
'http://www.google.com//services' AS ns1
)
SELECT
t.c.value('ns1:Name[1]', 'NVARCHAR(100)') AS name
FROM #x.nodes('//ns1:Info') as t(c);
We can read xml data in SQL Server as below:
DECLARE #xml XML =
'<DataTable>
<Employee>
<ID>100</ID>
<Name>Rohan</Name>
<Age>30</Age>
<Gender>Male</Gender>
<City>Delhi</City>
<State>Delhi</State>
</Employee>
</DataTable>'
SELECT
tbl.col.value('ID[1]', 'smallint') AS ID,
Tbl.Col.value('Name[1]', 'varchar(100)') AS Name,
Tbl.Col.value('Age[1]', 'smallint') AS Age,
Tbl.Col.value('Gender[1]', 'varchar(10)') AS Gender,
Tbl.Col.value('City[1]', 'varchar(50)') AS City,
Tbl.Col.value('State[1]', 'varchar(50)') AS State
FROM #xml.nodes('/DataTable/Employee') tbl(col)
To read more on how to read xml data visit below link
Read xml data as table in SQL Server
In case you want to read xml nodes dynamically with unknown number of elements, visit this link:
Read xml nodes dynamically in SQL Server
What am I not getting here? I can't get any return except NULL...
DECLARE #xml xml
SELECT #xml = '<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<SOAP-ENV:Body>
<webregdataResponse>
<result>0</result>
<regData />
<errorFlag>99</errorFlag>
<errorResult>Not Processed</errorResult>
</webregdataResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>'
DECLARE #nodeVal int
SELECT #nodeVal = #xml.value('(errorFlag)[1]', 'int')
SELECT #nodeVal
Here is the solution:
DECLARE #xml xml
SELECT #xml = '<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<SOAP-ENV:Body>
<webregdataResponse>
<result>0</result>
<regData />
<errorFlag>99</errorFlag>
<errorResult>Not Processed</errorResult>
</webregdataResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>'
declare #table table (data xml);
insert into #table values (#xml);
WITH xmlnamespaces (
'http://schemas.xmlsoap.org/soap/envelope/' as [soap])
SELECT Data.value('(/soap:Envelope/soap:Body/webregdataResponse/errorFlag)[1]','int') AS ErrorFlag
FROM #Table ;
Running the above SQL will return 99.
Snapshot of the result is given below,
That's because errorFlag is not the root element of your XML document. You can either specify full path from root element to errorFlag, for example* :
SELECT #nodeVal = #xml.value('(/*/*/*/errorFlag)[1]', 'int')
or you can use descendant-or-self axis (//) to get element by name regardless of it's location in the XML document, for example :
SELECT #nodeVal = #xml.value('(//errorFlag)[1]', 'int')
*: I'm using * instead of actual element name just to simplify the expression. You can also use actual element names along with the namespaces, like demonstrated in the other answer.
I have tried several ways to query this data out, but have not been successful. I am on SQL Server 2012. Any help would be appreciated.
<NewDataSet>
<Table>
<_x005B_M_x005D_._x005B_SEQID_x005D_ xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:short">200</_x005B_M_x005D_._x005B_SEQID_x005D_>
<_x005B_M_x005D_._x005B_CPID_x005D_ xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">1002</_x005B_M_x005D_._x005B_CPID_x005D_>
</Table>
</NewDataSet>
It would help to have more details on what exactly you want to get out of this, but here is a start, assuming each Element of the XML represents a row:
DECLARE #SampleData XML = N'
<NewDataSet>
<Table>
<_x005B_M_x005D_._x005B_SEQID_x005D_ xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:short">200</_x005B_M_x005D_._x005B_SEQID_x005D_>
<_x005B_M_x005D_._x005B_CPID_x005D_ xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">1002</_x005B_M_x005D_._x005B_CPID_x005D_>
</Table>
</NewDataSet>
';
DECLARE #Delim VARCHAR(50) = '._x005B_';
DECLARE #DelimLen INT = LEN(#Delim);
;WITH cte AS
(
SELECT xrow.value('local-name(.)', 'VARCHAR(50)') AS [ElementName],
xrow.value('declare namespace xsi="http://www.w3.org/2001/XMLSchema-instance"; (./#xsi:type)[1]', 'VARCHAR(50)') AS [xsi:type],
xrow.value('./text()[1]', N'VARCHAR(50)') AS [ElementValue]
FROM #SampleData.nodes('NewDataSet/Table/*') t(xrow)
)
SELECT *,
SUBSTRING(
cte.ElementName,
CHARINDEX(#Delim, cte.ElementName) + #DelimLen,
CHARINDEX('_',
cte.ElementName,
CHARINDEX(#Delim, cte.ElementName) + #DelimLen + 1) -
(CHARINDEX(#Delim, cte.ElementName) + #DelimLen)
) AS [RowType]
FROM cte;
Output:
ElementName xsi:type ElementValue RowType
_x005B_M_x005D_._x005B_SEQID_x005D_ xs:short 200 SEQID
_x005B_M_x005D_._x005B_CPID_x005D_ xs:string 1002 CPID
declare #demo xml = '<NewDataSet>
<Table>
<_x005B_M_x005D_._x005B_SEQID_x005D_ xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:short">200</_x005B_M_x005D_._x005B_SEQID_x005D_>
<_x005B_M_x005D_._x005B_CPID_x005D_ xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">1002</_x005B_M_x005D_._x005B_CPID_x005D_>
</Table>
</NewDataSet>'
select t.r.value('(./*[local-name()=''_x005B_M_x005D_._x005B_SEQID_x005D_'']/text())[1]','integer') seqid
, t.r.value('(./*[local-name()=''_x005B_M_x005D_._x005B_CPID_x005D_'']/text())[1]','nvarchar(128)') cpid
from #demo.nodes('/*/*') t(r)
SQL Fiddle: http://sqlfiddle.com/#!6/d41d8/21769