xml.exist - sql:column to sequence - sql

I try to create a query with xml.exist by using the sql:column-function where the value of the column should be transformed into a usable XQuery-sequence.
This is the query with a static sequence, which is working.
SELECT
FieldA
, FieldB
FROM
MyTable
WHERE
FieldC.exist('DSAuth/role[#id=("195", "267", "350")')
To get a dynamic sequence i would use a table function with returns a table with a column "IDsequence" that have all id's as a string. e.g. ' "195", "267", "350" '.
The table function should return only one row! With multiple rows it works, but i have to group the result at last, which is bad for performance.
SELECT
FieldA
, FieldB
FROM
MyTable
CROSS APPLY
dbo.MyFunc(0) AS f
WHERE
FieldC.exist('DSAuth/role[#id=sql:column("f.IDsequence")]')
Is there a way to get a usable sequence for XQuery from sql:column("f.IDsequence")?
Thanks for help.
Edit:
The problem in performance is that FieldB (and a few more fields) is a xml column, so i have to convert it to group by.
SELECT
FieldA
, CAST(CAST(FieldB AS nvarchar(max)) AS xml) AS FieldB
FROM
MyTable
CROSS APPLY
dbo.MyFunc(0) AS f
WHERE
FieldC.exist('DSAuth/role[#id=sql:column("f.IDsequence")]')
GROUP BY
FieldA
, CAST(FieldB AS nvarchar(max))

I don't know if this is the easiest approach, but you might try to include your list into the XML and use it in the predicate like here:
--A mockup-table to show the principles
DECLARE #tbl TABLE(TheXml XML)
INSERT INTO #tbl VALUES
(
N'<root>
<a>1</a>
<a>2</a>
</root>'
)
,(
N'<root>
<a>1</a>
</root>'
)
,(
N'<root>
<a>3</a>
<a>4</a>
</root>'
);
--This is easy: Just one value
SELECT * FROM #tbl WHERE TheXml.exist('/root/a[. cast as xs:int?=1]')=1;
--This is your sequence.
--But you cannot introduce the value list with sql:column() or sql:variable().
SELECT * FROM #tbl WHERE TheXml.exist('/root/a[. cast as xs:int?=(2,3)]')=1;
--But you can add the values to your XML before like in this cte
DECLARE #values TABLE(val INT);
INSERT INTO #values VALUES(2),(3);
WITH cte(NewXml) AS
(
SELECT (SELECT (SELECT val AS [#val] FROM #values FOR XML PATH('values'),TYPE)
,TheXml AS [*]
FOR XML PATH(''),TYPE
)
FROM #tbl t
)
SELECT NewXml.query('/root') TheXml
FROM cte
WHERE NewXml.exist('/root/a[. cast as xs:int?=/values/#val]')=1;
The intermediate XML looks like this:
<values val="2" />
<values val="3" />
<root>
<a>1</a>
<a>2</a>
</root>
The final .query('/root') will return the previous XML unchanged.
UPDATE
The same would work with an introduction on string base like here:
WITH cte(NewXml) AS
(
SELECT (SELECT CAST(N'<values val="2" /><values val="3" />' AS XML)
,TheXml AS [*]
FOR XML PATH(''),TYPE
)
FROM #tbl t
)
SELECT NewXml.query('/root') TheXml
FROM cte
WHERE NewXml.exist('/root/a[. cast as xs:int?=/values/#val]')=1

Related

Read multiple lines from xml column to table

I'm struggling reading data from measurements stored as xml columns. My xml files looks like this:
<Data t0="2018-09-18T07:43:11.882+01:00" dt="2.003338853E-5">
<Measurement>
<Value>2.075</Value>
<Value>2.175</Value>
<Value>2.275</Value>
<Value>2.325</Value>
<Value>2.425</Value>
...
</Measurement>
</Data>
What I need as result is a table containing the values.
What I already tried is this:
SELECT CONVERT(varchar(max),c.query('data(Value)')) as XMLValues
FROM [dbo].[T_Measurement] as t1
CROSS APPLY Measurement.nodes('/Data/Measurement') x(c)
which creates a resulting xml field with space separated values. But how can I create a query resulting in a table?
regards, Daniel
You can use query() to extract the values and then value to cast them to a numeric type:
declare #tmp table (Measurement xml)
insert into #tmp
select
'<Data t0="2018-09-18T07:43:11.882+01:00" dt="2.003338853E-5">
<Measurement>
<Value>2.075</Value>
<Value>2.175</Value>
<Value>2.275</Value>
<Value>2.325</Value>
<Value>2.425</Value>
</Measurement>
</Data>'
SELECT
Tbl.Col.value('.','decimal(18,3)') as XMLValues
FROM #tmp as t1
CROSS APPLY Measurement.nodes('/Data/Measurement/Value') Tbl(Col)
Result:
If you have multiple measurements in a single file (for example with an attribute that identifies each Measurement):
DECLARE #tmp TABLE (Measurement XML)
INSERT INTO #tmp
SELECT '<Data t0="2018-09-18T07:43:11.882+01:00" dt="2.003338853E-5">
<Measurement setId="1">
<Value>1.075</Value>
<Value>1.175</Value>
<Value>1.275</Value>
<Value>1.325</Value>
<Value>1.425</Value>
</Measurement>
<Measurement setId="2">
<Value>2.076</Value>
<Value>2.176</Value>
<Value>2.276</Value>
<Value>2.326</Value>
<Value>2.426</Value>
</Measurement>
</Data>'
SELECT
Tbl.Col.value('../#setId', 'int') as setId,
Tbl.Col.value('.', 'decimal(18,3)') as XMLValues
FROM #tmp AS t1
CROSS APPLY Measurement.nodes('/Data/Measurement/Value') Tbl(Col)
Results:

Generate XML of the Structure of a table when it's empty in SQL Server

I am trying to generate a table containing one row that contains the XML of each temporary table in a stored procedure.
The problem is when the table is empty the FOR XML PATH('RS'), root('OR_RS') returns null.
What I want is: when the table is empty, return the structure of this table
something like this :
<OR_RS>
<ContactCode></ContactCode>
<EmailPaper></EmailPaper>
<ShortEmail></ShortEmail>
<WebSite></WebSite>
<Providers></Providers>
</OR_RS>
I have tried to do this :
-- ,ISNULL( (SELECT * FROM #OR_RS FOR XML PATH('RS'), root('OR_RS')), (SELECT ISNULL(ContactCode,'') , ISNULL(EmailPaper,'') , ISNULL(ShortEmail,'') , ISNULL(WebSite,'') , ISNULL(Providers,'') FROM #OR_RS FOR XML RAW)) as OR_RS
but it returns always Null:
SELECT 1 as Id, (SELECT * FROM #OR_MK FOR XML PATH('MK'), root('OR_MK') ) as OR_MK
,(SELECT * FROM #OR_CA FOR XML PATH('CA'), root('OR_CA') ) as OR_CA
-- ,ISNULL( (SELECT * FROM #OR_RS FOR XML PATH('RS'), root('OR_RS')), (SELECT ISNULL(ContactCode,'') , ISNULL(EmailPaper,'') , ISNULL(ShortEmail,'') , ISNULL(WebSite,'') , ISNULL(Providers,'') FROM #OR_RS FOR XML AUTO)) as OR_RS
,(SELECT * FROM #OR_RS FOR XML PATH('RS'), root('OR_RS')) as OR_RS
,(SELECT * FROM #OR_DC FOR XML PATH('DC'), root('OR_DC') ) as OR_DC
,(SELECT * FROM #BENEFICIARY FOR XML PATH('BEN'), root('BENEFICIARY') ) as BENEFICIARY
,(SELECT * FROM #MK_REPORT for XML PATH('REP'), root('MK_REPORT')) as MK_REPORT
Whatever you try to do with this...
You might want to have a look at sp_describe_first_result_set, but, since this is a procedure, it will not be that easy to get its result into your query...
You can use a trick (a RIGHT JOIN) to enforce a resultset. And with ELEMENTS XSINIL you force the engine to include the column in any case. Otherwise XML takes missing elements as NULL, so your empty result would not be written into the result XML at all otherwise. Try this:
DECLARE #tbl TABLE(ID INT IDENTITY,SomeValue INT,SomeString VARCHAR(100));
SELECT *
FROM #tbl
RIGHT JOIN (SELECT 1 AS x) AS tbl ON 1=1
FOR XML RAW, ELEMENTS XSINIL
The result
<row xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ID xsi:nil="true" />
<SomeValue xsi:nil="true" />
<SomeString xsi:nil="true" />
<x>1</x>
</row>
If you want to get more details, you might add ,XMLDATA or ,XMLSCHEMA to generate full meta data.

Query XML field in SQL Server

I am using sql server 2008 R2. I have table X with Column XXML with the following structure
<rec>
<set>
<Raw CLOrderID="GGM-30-08/24/10" Rej="Preopen" Sym="A" Tm="06:36:29.524" />
</set>
</rec>
I want to parse above column XXML and return output as below:
CLOrderID Rej Sym Tm
GGM-30-08/24/10 Preopen A 06:36:29.524
Use nodes() to shred the XML and value() to extract the attribute values.
select T.X.value('#CLOrderID', 'nvarchar(100)') as CLOrderID,
T.X.value('#Rej', 'nvarchar(100)') as Rej,
T.X.value('#Sym', 'nvarchar(100)') as Sym,
T.X.value('#Tm', 'time(3)') as Tm
from dbo.X
cross apply X.XXML.nodes('/rec/set/Raw') as T(X)
If you know for sure that you only will have one row extracted for each XML you can get the attribute values directly without shredding first.
select X.XXML.value('(/rec/set/Raw/#CLOrderID)[1]', 'nvarchar(100)') as CLOrderID,
X.XXML.value('(/rec/set/Raw/#Rej)[1]', 'nvarchar(100)') as Rej,
X.XXML.value('(/rec/set/Raw/#Sym)[1]', 'nvarchar(100)') as Sym,
X.XXML.value('(/rec/set/Raw/#Tm)[1]', 'time(3)') as Tm
from dbo.X
This can be done with a few for xml calls. This structure also remains flexible for future schema changes, provided /rec/set/Raw/#* is present. If that changes, you can always add a pipe with the new path for the attributes you're wanting to grab. Hope this helps.
declare #x table (id int identity(1,1) primary key, x xml)
insert into #x (x) values ('<rec>
<set>
<Raw CLOrderID="GGM-30-08/24/10" Rej="Preopen" Sym="A" Tm="06:36:29.524" />
</set>
</rec>')
select a.id, cast((
select (
select x.attribs.value('local-name(.)','nvarchar(20)') + ' '
from #x t
outer apply t.x.nodes('/rec/set/Raw/#*') x(attribs)
where t.id = a.id
for xml path('')
), (
select x.attribs.value('.','nvarchar(20)') + ' '
from #x t
outer apply t.x.nodes('/rec/set/Raw/#*') x(attribs)
where t.id = a.id
for xml path('')
)
for xml path('')
) as varchar(500))
from #x a

SQL: How can I get the value of an attribute in XML datatype?

I have the following xml in my database:
<email>
<account language="en" ... />
</email>
I am using something like this now: but still have to find the attribute value.
SELECT convert(xml,m.Body).query('/Email/Account')
FROM Mail
How can I get the value of the language attribute in my select statement with SQL?
Use XQuery:
declare #xml xml =
'<email>
<account language="en" />
</email>'
select #xml.value('(/email/account/#language)[1]', 'nvarchar(max)')
declare #t table (m xml)
insert #t values
('<email><account language="en" /></email>'),
('<email><account language="fr" /></email>')
select m.value('(/email/account/#language)[1]', 'nvarchar(max)')
from #t
Output:
en
fr
This should work:
DECLARE #xml XML
SET #xml = N'<email><account language="en" /></email>'
SELECT T.C.value('#language', 'nvarchar(100)')
FROM #xml.nodes('email/account') T(C)
It depends a lot on how you're querying the document. You can do this, though:
CREATE TABLE #example (
document NText
);
INSERT INTO #example (document)
SELECT N'<email><account language="en" /></email>';
WITH XmlExample AS (
SELECT CONVERT(XML, document) doc
FROM #example
)
SELECT
C.value('#language', 'VarChar(2)') lang
FROM XmlExample CROSS APPLY
XmlExample.doc.nodes('//account') X(C);
DROP TABLE #example;
EDIT after changes to your question.
if the xml data is stored in sql server as a string column then use cast
select cast(your_field as XML)
.value('(/email/account/#language)[1]', 'varchar(20)')
from your_table

Concatenate multiple xml columntype rows in SQL

I have an online form, whereby each entry adds the data as xml to an xml column in SQL.
ApplicationID(uniqueidentifier) | DateModified | ApplicationForm(XML)
What I need to do is perform a select query that will grab all the ApplicationForm xml values, and concatenate them together to form one result, e.g.
Row1: <ApplicationForm type=""></ApplicationForm>
Row2: <ApplicationForm type=""></ApplicationForm>
Select result:
<Applications>
<ApplicationForm type=""></ApplicationForm>
<ApplicationForm type=""></ApplicationForm>
</Applications>
Probably a better way to do it than this, but I specified the ApplicationForm tag as a tag to be removed, and then stripped it out.
DECLARE #a TABLE (ID UNIQUEIDENTIFIER,
DateModified DATETIME,
ApplicationForm XML)
INSERT INTO #a
( ID, DateModified, ApplicationForm )
VALUES ( NEWID(), -- ID - uniqueidentifier
'2010-12-07 18:47:36', -- DateModified - datetime
'<Application><Form>123</Form></Application>'
) ,
( NEWID(), -- ID - uniqueidentifier
'2010-12-07 18:47:36', -- DateModified - datetime
'<Application><Form>456</Form></Application>'
)
DECLARE #Result VARCHAR(MAX)
SET #Result = CONVERT(VARCHAR(MAX), ( SELECT ApplicationForm AS "StripTagOut"
FROM #a
FOR XML PATH(''), ROOT('Applications'), TYPE ))
SELECT CONVERT(xml, REPLACE(REPLACE(#Result, '</StripTagOut>', ''), '<StripTagOut>', ''))
This was an experiment in using XML EXPLICIT which I believe works:
SELECT 1 AS Tag,
NULL AS Parent,
NULL [Applications!1],
NULL [ApplicationForm!2!!XMLTEXT]
UNION ALL
SELECT 2 AS Tag,
1 AS Parent,
NULL [Applications!1],
ApplicationForm [ApplicationForm!2!!XMLTEXT]
FROM YourTable
FOR XML EXPLICIT
For my own gratification, here is the sample script I used
CREATE TABLE XmlTest
(
ApplicationForm xml
)
INSERT INTO XmlTest VALUES ('<ApplicationForm type="a"><SomeTag>SomeContent</SomeTag></ApplicationForm>')
INSERT INTO XmlTest VALUES ('<ApplicationForm type="b"><SomeTag>SomeOtherContent</SomeTag></ApplicationForm>')
SELECT 1 AS Tag,
NULL AS Parent,
NULL [Applications!1],
NULL [ApplicationForm!2!!XMLTEXT]
UNION ALL
SELECT 2 AS Tag,
1 AS Parent,
NULL [Applications!1],
ApplicationForm [ApplicationForm!2!!XMLTEXT]
FROM XmlTest
FOR XML EXPLICIT
Which output
<Applications>
<ApplicationForm type="a">
<SomeTag>SomeContent</SomeTag>
</ApplicationForm>
<ApplicationForm type="b">
<SomeTag>SomeOtherContent</SomeTag>
</ApplicationForm>
</Applications>
Take a look at this page, which lists quite a number of ways to concatenate rows of data.