Get XML output from SQL query [closed] - sql-server

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
I am writing SQL query to get output as below . I am not using any tables from database.
A query to get the desired output as
<Property ID="0" Name="Color" NumOfItems="11">
<Item ID="0" Name="D"/>
<Item ID="1" Name="E"/>
<Item ID="2" Name="F"/>
<Item ID="3" Name="G"/>
<Item ID="4" Name="H"/>
<Item ID="5" Name="I"/>
<Item ID="6" Name="J"/>
<Item ID="7" Name="K"/>
<Item ID="8" Name="L"/>
<Item ID="9" Name="M"/>
<Item ID="10" Name="N"/>
</Property>
I tried as this
SELECT
(
SELECT '0' AS 'Item/#ID','D' AS 'Item/#Name' FOR XML PATH(''), TYPE ),
(SELECT '1' AS 'Item/#ID','E' AS 'Item/#Name' FOR XML PATH(''), TYPE ),
(SELECT '2' AS 'Item/#ID','F' AS 'Item/#Name' FOR XML PATH(''), TYPE ),
(SELECT '3' AS 'Item/#ID','G' AS 'Item/#Name' FOR XML PATH(''), TYPE ),
(SELECT '4' AS 'Item/#ID','H' AS 'Item/#Name' FOR XML PATH(''), TYPE ),
(SELECT '5' AS 'Item/#ID','I' AS 'Item/#Name' FOR XML PATH(''), TYPE ),
(SELECT '6' AS 'Item/#ID','J' AS 'Item/#Name' FOR XML PATH(''), TYPE ),
(SELECT '7' AS 'Item/#ID','K' AS 'Item/#Name' FOR XML PATH(''), TYPE ),
(SELECT '8' AS 'Item/#ID','L' AS 'Item/#Name' FOR XML PATH(''), TYPE ),
(SELECT '9' AS 'Item/#ID','M' AS 'Item/#Name' FOR XML PATH(''), TYPE ),
(SELECT '10' AS 'Item/#ID','N' AS 'Item/#Name' FOR XML PATH(''), TYPE )
FOR XML PATH(''),
ROOT('Property'),TYPE

I am not using any tables from database
Well just SELECT it...
SELECT CAST ('<Property ID="0" Name="Color" NumOfItems="11">
<Item ID="0" Name="D"/>
<Item ID="1" Name="E"/>
<Item ID="2" Name="F"/>
<Item ID="3" Name="G"/>
<Item ID="4" Name="H"/>
<Item ID="5" Name="I"/>
<Item ID="6" Name="J"/>
<Item ID="7" Name="K"/>
<Item ID="8" Name="L"/>
<Item ID="9" Name="M"/>
<Item ID="10" Name="N"/>
</Property>' AS XML)

1)
SELECT *
FROM (VALUES (0, 'Color', 11)) Property(ID, Name, NumOfItems)
JOIN (VALUES (0,0,'D'), (0,1,'E'), (0,2,'F')) Item(PropertyID,ID,Name)
ON Property.ID = Item.PropertyID
FOR XML AUTO
Output:
<Property ID="0" Name="Color" NumOfItems="11">
<Item PropertyID="0" ID="0" Name="D" />
<Item PropertyID="0" ID="1" Name="E" />
<Item PropertyID="0" ID="2" Name="F" />
</Property>
2)
SELECT *,
(SELECT * FROM (VALUES (0,'D'), (1, 'E'), (2, 'F')) MamboJambo("#ID", "#Name") FOR XML PATH('Item'),TYPE)
FROM (VALUES (0,'Color',11)) CocoJambo("#ID", "#Name", "#NumOfItems")
FOR XML PATH('Property')
3)
SELECT CONVERT(XML, N'<Property ID="0" Name="Color" NumOfItems="11">
<Item ID="0" Name="D"/>
<Item ID="1" Name="E"/>
<Item ID="2" Name="F"/>
</Property>').query(N'
for $x in (/Property)
return
<Property ID="{$x/#ID}" Name="{$x/#Name}" NumOfItems="{$x/#NumOfItems}" >
{for $y in ($x/Item) return $y}
</Property>
');

Related

Inserting XML data in to a table

I need to insert an external XML file data into a SQL Server table. I tried the below code. But this inserts a single record with NULL values for all the columns
Declare #xml XML
Select #xml =
CONVERT(XML,bulkcolumn,2) FROM OPENROWSET(BULK
'C:\Users\PC901\Downloads\Tags.xml',SINGLE_BLOB) AS X
SET ARITHABORT ON
TRUNCATE TABLE Tags
Insert into Tags
(
ID,WikiPostId,ExcerptPostId,Count,TagName
)
Select
P.value('ID[1]','BIGINT') AS ID,
P.value('WikiPostId[1]','BIGINT') AS WikiPostId,
P.value('ExcerptPostId[1]','BIGINT') AS ExcerptPostId,
P.value('Count[1]','BIGINT') AS Count,
P.value('TagName[1]','VARCHAR(100)') AS TagName
From #xml.nodes('/tags') PropertyFeed(P)
SELECT * FROM Tags
and the sample XML would be
<?xml version="1.0" encoding="utf-8"?>
<tags>
<row Id="1" TagName=".net" Count="283778" ExcerptPostId="3624959" WikiPostId="3607476" />
<row Id="2" TagName="html" Count="826083" ExcerptPostId="3673183" WikiPostId="3673182" />
<row Id="3" TagName="javascript" Count="1817846" ExcerptPostId="3624960" WikiPostId="3607052" />
<row Id="4" TagName="css" Count="588062" ExcerptPostId="3644670" WikiPostId="3644669" />
<row Id="5" TagName="php" Count="1286873" ExcerptPostId="3624936" WikiPostId="3607050" />
</tags>
Here you go:
declare #xml xml = '<?xml version="1.0" encoding="utf-8"?>
<tags>
<row Id="1" TagName=".net" Count="283778" ExcerptPostId="3624959" WikiPostId="3607476" />
<row Id="2" TagName="html" Count="826083" ExcerptPostId="3673183" WikiPostId="3673182" />
<row Id="3" TagName="javascript" Count="1817846" ExcerptPostId="3624960" WikiPostId="3607052" />
<row Id="4" TagName="css" Count="588062" ExcerptPostId="3644670" WikiPostId="3644669" />
<row Id="5" TagName="php" Count="1286873" ExcerptPostId="3624936" WikiPostId="3607050" />
</tags>'
Select
P.value('#Id','BIGINT') AS ID,
P.value('#WikiPostId','BIGINT') AS WikiPostId,
P.value('#ExcerptPostId','BIGINT') AS ExcerptPostId,
P.value('#Count','BIGINT') AS Count,
P.value('#TagName','VARCHAR(100)') AS TagName
From #xml.nodes('/tags/row') PropertyFeed(P)
outputs
ID WikiPostId ExcerptPostId Count TagName
----------- -------------------- -------------------- -------------------- ----------
1 3607476 3624959 283778 .net
2 3673182 3673183 826083 html
3 3607052 3624960 1817846 javascript
4 3644669 3644670 588062 css
5 3607050 3624936 1286873 php
(5 rows affected)

SQL Server stored procedure - Table to XML object

I need to write a stored procedure that can create the following output from values from a SQL Server table:
<object>
<ValueList>
<Value value="1" text="Name" enabled="1" alias="Alias" />
<Value value="2" text="Name" enabled="1" alias="Alias" />
<Value value="3" ....
...
...
</ValueList>
</object>
I have tried to convert my table into XML using this procedure:
select TXT as [text]
from lit_geography
for XML raw ('value'), root('object')
Then I get the following
<object>
<value text="Midler tidig havn" />
<value text="Færgehavnsvej" />
<value text="Sydhavnsvej" />
<value text="Ø-Pladsen" />
<value text="Havnepladsen" />
</object>
TODO:
I am missing the parent node Valuelist
I need to append the following:
value="1", value="2" etc etc counting up for each value
enabled="1"
alias=""
For the incremental value, you can use Row_Number()
Example
Select (
Select [value] = row_number() over (Order by (select null))
,[text] = txt
,[enabled] = 1
,[alias] = 'Alias'
From lit_geography
For XML Raw('Value'),type
)
For XML Path('ValueList'),Root('object')
Returns
<object>
<ValueList>
<Value value="1" text="Midler tidig havn" enabled="1" alias="Alias" />
<Value value="2" text="Færgehavnsvej" enabled="1" alias="Alias" />
<Value value="3" text="Sydhavnsvej" enabled="1" alias="Alias" />
<Value value="4" text="Ø-Pladsen" enabled="1" alias="Alias" />
<Value value="5" text="Havnepladsen" enabled="1" alias="Alias" />
</ValueList>
</object>
EDIT - Requested UPDATE
Update lit_formfield set [Values] = (
Select (
Select [value] = row_number() over (Order by (select null))
,[text] = txt
,[enabled] = 1
,[alias] = 'Alias'
From lit_geography
For XML Raw('Value'),type
)
For XML Path('ValueList'),Root('object')
)
Where Label = 'listbox'

Split xml into smaller pieces

I have an xml variable.
DECLARE #xml xml = N'<Items Category="AAA">
<Item Id="1">A</Item>
<Item Id="2">B</Item>
<Item Id="3">C</Item>
<Item Id="4">D</Item>
<Item Id="5">E</Item>
<Item Id="6">F</Item>
<Item Id="7">G</Item>
<Item Id="8">H</Item>
<Item Id="9">I</Item>
</Items>'
Could you help me write a query to split it into several pieces?
<Items Category="AAA">
<Item Id="1">A</Item>
<Item Id="2">B</Item>
<Item Id="3">C</Item>
</Items>
<Items Category="AAA">
<Item Id="4">D</Item>
<Item Id="5">E</Item>
<Item Id="6">F</Item>
</Items>
<Items Category="AAA">
<Item Id="7">G</Item>
<Item Id="8">H</Item>
<Item Id="9">I</Item>
</Items>
I mean XQuery, but any other idea is welcome.
Way to do this via XQuery modify:
DECLARE #xml xml = N'<Items Category="AAA">
<Item Id="1">A</Item>
<Item Id="2">B</Item>
<Item Id="3">C</Item>
<Item Id="4">D</Item>
<Item Id="5">E</Item>
<Item Id="6">F</Item>
<Item Id="7">G</Item>
<Item Id="8">H</Item>
<Item Id="9">I</Item>
</Items>';
DECLARE #temp TABLE (XmlData1 xml, XmlData2 xml, XmlData3 xml);
INSERT #temp VALUES (#xml, #xml, #xml);
UPDATE t
SET XmlData1.modify('delete /Items/Item[not(position() >= 1 and position() < 4)]'),
XmlData2.modify('delete /Items/Item[not(position() >= 4 and position() < 7)]'),
XmlData3.modify('delete /Items/Item[not(position() >= 7 and position() < 10)]')
FROM #temp t;
SELECT * FROM #temp;
Way to do this via FLWOR:
select #xml.query('
<Items Category="AAA">
{
for $item in /Items/Item[position() >= 1 and position() < 4]
return $item
}
</Items>');
You can freely change your split criteria in XPath.

How to Insert xml data into SQL Server table?

How to import below XML data into SQL Server table with three columns?
<dataset>
<metadata>
<item name="NAME_LAST" type="xs:string" length="62" />
<item name="NAME_FIRST" type="xs:string" length="62" />
<item name="NAME_MIDDLE" type="xs:string" length="32" />
</metadata>
<data>
<row>
<value>SMITH</value>
<value>MARY</value>
<value>N</value>
</row>
<row>
<value>SMITH2</value>
<value>MARY2</value>
<value>N2</value>
</row>
</data>
</dataset>
Try this:
DECLARE #input XML = '<dataset>
<metadata>
<item name="NAME_LAST" type="xs:string" length="62" />
<item name="NAME_FIRST" type="xs:string" length="62" />
<item name="NAME_MIDDLE" type="xs:string" length="32" />
</metadata>
<data>
<row>
<value>SMITH</value>
<value>MARY</value>
<value>N</value>
</row>
<row>
<value>SMITH2</value>
<value>MARY2</value>
<value>N2</value>
</row>
</data>
</dataset>'
INSERT INTO dbo.YourTable(ColName, ColFirstName, ColOther)
SELECT
Name = XCol.value('(value)[1]','varchar(25)'),
FirstName = XCol.value('(value)[2]','varchar(25)'),
OtherValue = XCol.value('(value)[3]','varchar(25)')
FROM
#input.nodes('/dataset/data/row') AS XTbl(XCol)
Insert XML Data into sql Server table
Declare #retValue1 varchar(50);
Declare #XmlStr XML;
SET #XmlStr='<Customers>
<customer>
<ID>111589</ID>
<FirstName>name1</FirstName>
<LastName>Lname1</LastName>
<Company>ABC</Company>
</customer>
<customer>
<ID>12345</ID>
<FirstName>name2</FirstName>
<LastName>Lname2</LastName>
<Company>ABC</Company>
</customer>
<customer>
<ID>14567</ID>
<FirstName>name3</FirstName>
<LastName>Lname3</LastName>
<Company>DEF</Company>
</customer>
</Customers>';
#retValue='Failed';
INSERT INTO [test_xmlinsert](
[id],
[firstName],
[lastName],
[company]
)
SELECT
COALESCE([Table].[Column].value('ID[1]', 'int'),0) as 'ID',
[Table].[Column].value('FirstName [1]', 'varchar(50)') as ' FirstName ',
[Table].[Column].value(' LastName[1]', 'varchar(50)') as ' LastName',
[Table].[Column].value(' Company [1]', 'varchar(50)') as ' Company'
FROM #XmlStr.nodes('/ Customers / customer') as [Table]([Column])
IF(##ROWCOUNT > 0 )
SET #retValue='SUCCESS';

xml.value() method in SQL Server (Getting a value inside an XML query)

I have an XML Query like this:
<ChangeSet xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Change DateTime="2011-12-02T09:01:58.3615661-08:00" UserId="3123">
<Table ChangeType="Insert" Name="EVNT_LN_AFF">
<Keys>
<Key FieldName="DIR_CD" Value="NB" />
<Key FieldName="LN_ID" Value="A" />
<Key FieldName="EVNT_ID" Value="10T000289" />
</Keys>
<ChangedFields>
<Field FieldName="DIR_CD" Previous="" Current="NB" />
<Field FieldName="LN_ID" Previous="" Current="A" />
<Field FieldName="EVNT_ID" Previous="" Current="10T000289" />
<Field FieldName="UD_DTTM" Previous="" Current="12/2/2011 9:01:59 AM" />
<Field FieldName="UD_USER_ID" Previous="" Current="3123" />
</ChangedFields>
</Table>
(The query goes on)
Now I want to use a statement like this:
SELECT TOP 1000 [CHG_LOG_ID]
, [EVNT_ID]
, [DATA_XML_TXT]
, [UD_DTTM]
FROM [MY_PROJ].[dbo].[EVNT_CHG_LOG]
WHERE DATA_XML_TXT.value('(/ChangeSet/Change/Table/ChangedFields/UD_USER_ID)[0]','varchar(50)') like '%3123%'
But when I execute the query, I don't get any results.
I tested the following XQuery, and it should give you what you need:
SELECT TOP 1000 [CHG_LOG_ID]
, [EVNT_ID]
, [DATA_XML_TXT]
, [UD_DTTM]
FROM [MY_PROJ].[dbo].[EVNT_CHG_LOG]
WHERE DATA_XML_TXT.value('(/ChangeSet/Change/Table/ChangedFields/Field[#FieldName="UD_USER_ID"]/#Current)[1]','varchar(50)') like '%3123%'
Note: Indexing for XQuery starts at 1 instead of 0

Resources