Creating xml for SQL Server stored procedure - sql

I have a function to insert an item into the database. It takes a lot of values as input and the values are passed as XML.
Consider a sample item XML:
<ROOT>
<Item
ItemName="CarlsApplication"
ItemTypeID="2">
<TSDefaultDescription DefaultitemDescription="C:\t.text"/>
<ItemSellers>
<ComputerObject Alias="" DisplayName="" ServiceName="" UserAccount="" />
<ComputerObject Alias="" DisplayName="" ServiceName="" UserAccount="" />
</ItemSellers>
<ItemOwners>
<ItemOwner Alias="rafchen" FirstName="Rafael" LastName="Chenkov"/>
</ItemOwners>
</Item>
</ROOT>
This has to be passed to stored procedure.
Now, each of these individual values in this XML, I have to extract from somewhere else. I can get the individual values like Item name etc, but how do I organize them into an XML that can be passed?
How do I construct this XML from the values I have?
I guess I will have to make some sort of template with this format and then put variables in that template and fill the variables to prepare the template.
Any help is greatly appreciated.

If I understand what you really want, You can use a query like this to generate that XML:
select
ItemName 'Item/#ItemName', --> Node:`Item` Attribute: `ItemName`
ItemTypeId 'Item/#ItemTypeId',
cast((
select
Alias 'ComputerObject/#Alias',
DisplayName 'ComputerObject/#DisplayName',
ServiceName 'ComputerObject/#ServiceName',
UserAccount 'ComputerObject/#UserAccount'
from
ItemSellers
where
ItemSellers.ItemId = Item.ItemId
for xml path('')) as xml) 'Item/ItemSellers', --> Node:`Item` Sub-Node:`ItemSellers`
cast((
select
Alias 'ItemOwner/#Alias',
FirstName 'ItemOwner/#FirstName',
LastName 'ItemOwner/#LastName'
from
ItemOwners
where
ItemOwners.ItemId = Item.ItemId
for xml path('')) as xml) 'Item/ItemOwners'
from
Item
for xml path('ROOT');
SQL Fiddle Demo

Related

SQL query for XML data

I have a SQL Server database table with a column called XML that contains XML data which is structured like this:
<Item xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://test/data">
<Roots>
<Root>
<Name>Field Name</Name>
<Value>Field Value</Value>
</Root>
<Root>
<Name>Field Name</Name>
<Value>Field Value</Value>
</Root>
</Roots>
I want to use T-SQL to get the Value where Name = Total. I have tried the following but it isn't returning any data:
SELECT [XML]
FROM [BusinessAccount]
WHERE [XML].value('(/Root/Name)[13]', 'VARCHAR(MAX)') LIKE '%Total%'
If anyone could tell me where I've gone wrong?
You are missing the required WITH XMLNAMESPACES for your XML and the path is incorrect.
If you want to bring back rows where the 13th element consists of the text Total you can use the below.
WITH XMLNAMESPACES (DEFAULT 'http://test/data')
SELECT [XML]
FROM [BusinessAccount]
WHERE 1 = [XML].exist('(/Item/Roots/Root/Name)[13][text() = "Total"]')
Otherwise you can add the WITH XMLNAMESPACES to your original query and fix the path there too.
You need to specify namespaces. You can then match <Name> and <Value> pairs and extract the contents of <Value> like so:
SELECT NameNode.value('declare namespace x="http://test/data"; (../x:Value)[1]', 'varchar(100)')
FROM [BusinessAccount]
CROSS APPLY [XML].nodes('declare namespace x="http://test/data"; //x:Root/x:Name') AS n(NameNode)
WHERE NameNode.value('.', 'varchar(100)') = 'Total'
Demo on db<>fiddle

Select multiple values in XML file and concatenation them with xQuery

I have the following XML:
<items>
<item value="1"/>
<item value="2"/>
<item value="4"/>
</items>
and I would like to select all item value and concatenate them like this - see below - with XQuery :
1.2.4
Any ideas?
Thanks in advance.
There are two parts to your question:
getting values out of xml
concatenating multiple values together
The second part of your question has been covered off very nicely in the answers to this question.
In terms of getting the values out of your xml, try the below:
-- Your xml variable
DECLARE #xml AS XML = '<items>
<item value="1"/>
<item value="2"/>
<item value="4"/>
</items>'
-- Example of selecting the values into rows
SELECT
item.value('.', 'int')
FROM
#xml.nodes('/items/item/#value') as T1(item)
-- Use your favourite/'best for your circumstance' method of
-- concatenating the rows into one string
-- see https://stackoverflow.com/q/194852/1208914 for other ways
SELECT
item.value('.', 'varchar(50)') + ' ' as 'data()'
FROM
#xml.nodes('/items/item/#value') as T1(item)
for xml path('')
I've put the code above into a sql fiddle that you can access and play with here: http://sqlfiddle.com/#!6/d41d8/18144/0
Using XQuery you can simply select the values using XPath and join them together using a dot.
string-join(/items/item/#value, '.')

XML sql query , attribute as column

I need to query xml data available in server
<root>
<Parameter>
<Param>APP_REG_NUMBER</Param>
<Value>AL/T/2010/86</Value>
</Parameter>
<Parameter>
<Param>SUBLINEID</Param>
<Value>235931</Value>
</Parameter>
</root>
This is the structure I am saving data into SQL Server, I need output as follows:
Filed1 , Filed2 , APP_REG_NUMBER, SUBLINEID
something something , AL/T/2010/86, 235931
please do the needful
You can use XQuery for this, but realize you are recreating key-value-pairs in XML, which negates the ability to use schemas or XQuery/XPATH in any reasonable manner. Consider changing the format to:
<root>
<APP_REG_NUMBER>AL/T/2010/86</APP_REG_NUMBER>
<SUBLINEID>235931</SUBLINEID>
</root>
I digress... the query you want is:
DECLARE #testXml xml = N'<root>
<Parameter><Param>APP_REG_NUMBER</Param><Value>AL/T/2010/86</Value></Parameter>
<Parameter><Param>SUBLINEID</Param><Value>235931</Value></Parameter>
</root>'
SELECT
#testXml.value('(//Parameter[Param/text()="APP_REG_NUMBER"]/Value)[1]', 'nvarchar(50)') as APP_REG_NUMBER,
#testXml.value('(//Parameter[Param/text()="SUBLINEID"]/Value)[1]', 'nvarchar(50)') as SUBLINEID
You use the //Parameter syntax to find all Parameter elements and then filter them ([Param/text()="foobar"]) to only those which have a child named Value that have the inner text of SUBLINEID. From there, you navigate to the /Value child element and return the first result ((query)[1]).

selecting an attribute from XML in SQL

Okay, I have a table that has a column called bdParameters, datatype is text. The data stored in the bdParameters column is XML saved as text.
The data goes like this:
<root>
<row statusID="ALL" subID="ALL" viewMaskFields="false" masID="219"
userID="13" prptyDate="08/19/2011" docID="21b15c9e-76a5-44ed-afbb-96b6df2cf881"
resmID="8806" leaID="6345" reshID="3560" doEmail="" emailFrom="" emailTo=""
emailMsg="penarands" emailSubject="" fieldList="1" fmtID="2" OptInCES="Yes"
SendVaiEmailCES="1" RPIPMCURL="blabla#blabla.com" />
<Custom>
<UpdateResidentLetter>
<Row Status="NOTPRINTED" Notes="Created from bulk lettersinterface" />
</UpdateResidentLetter>
</Custom>
</root>
I want to be able to select only the attribute emailMsg from that xml.
Is that possible? If so, how?
Use xml.value with the # symbol to get the attribute
declare #t table (col xml);
insert #t select '
<root><row statusID="ALL" subID="ALL" viewMaskFields="false" masID="219"
userID="13" prptyDate="08/19/2011" docID="21b15c9e-76a5-44ed-afbb-96b6df2cf881"
resmID="8806" leaID="6345" reshID="3560" doEmail="" emailFrom="" emailTo=""
emailMsg="penarands" emailSubject="" fieldList="1" fmtID="2" OptInCES="Yes"
SendVaiEmailCES="1" RPIPMCURL="lm-10-254-9-52.onesitedev.realpage.com" /><Custom>
<UpdateResidentLetter><Row Status="NOTPRINTED" Notes="Created from bulk letters
interface" /></UpdateResidentLetter></Custom></root>';
select col.value('(/root/row/#emailMsg)[1]','varchar(max)') emailMsg
from #t
-- result
penarands

How do I select a top-level attribute of an XML column in SQL Server?

I have an XML column in SQL Server that is the equivalent of:
<Test foo="bar">
<Otherstuff baz="belch" />
</Test>
I want to get the value of the foo attribute of Test (the root element) as a varchar. My goal would be something along the lines of:
SELECT CAST('<Test foo="bar"><Otherstuff baz="belch" /></Test>' AS xml).value('#foo', 'varchar(20)') AS Foo
But when I run the above query, I get the following error:
Msg 2390, Level 16, State 1, Line 1
XQuery [value()]: Top-level attribute
nodes are not supported
John Saunders has it almost right :-)
declare #Data XML
set #Data = '<Test foo="bar"><Otherstuff baz="belch" /></Test>'
select #Data.value('(/Test/#foo)[1]','varchar(20)') as Foo
This works for me (SQL Server 2005 and 2008)
Marc
If you dont know the root element:
select #Data.value('(/*/#foo)[1]','varchar(20)') as Foo
Why does .value('#foo', 'varchar(20)') generate the error “Top-level attribute nodes are not supported”?
When you query the xml data type, the context is the document node, which is an implicit node that contains the root element(s) of your XML document. The document node has no name and no attributes.
How can I get the value of an attribute on the root element?
In your XQuery expression, include the path to the first root element:
DECLARE #Data xml = '<Customer ID="123"><Order ID="ABC" /></Customer>'
SELECT #Data.value('Customer[1]/#ID', 'varchar(20)')
-- Result: 123
If you don’t know (or don’t want to specify) the name of the root element, then just use * to match any element:
SELECT #Data.value('*[1]/#ID', 'varchar(20)')
-- Result: 123
Because the query context is the document node, you don’t need to prefix the XQuery expression with a forward slash (as the other answers unnecessarily do).
Why do I have to include [1]?
The XQuery expression you pass to value() must be guaranteed to return a singleton. The expression Customer/#ID doesn’t satisfy this requirement because it matches both ID="123" and ID="456" in the following example:
DECLARE #Data xml = '<Customer ID="123" /><Customer ID="456" />'
Remember that the xml data type represents an XML document fragment, not an XML document, so it can contain multiple root elements.
What’s the difference between Customer[1]/#ID and (Customer/#ID)[1]?
The expression Customer[1]/#ID retrieves the ID attribute of the first <Customer> element.
The expression (Customer/#ID)[1] retrieves the ID attribute of all <Customer> elements, and from this list of attributes, picks the first.
The following example demonstrates the difference:
DECLARE #Data xml = '<Customer /><Customer ID="123" /><Customer ID="456" />'
SELECT #Data.value('Customer[1]/#ID', 'varchar(20)')
-- Result: NULL (because the first Customer element doesn't have an ID attribute)
SELECT #Data.value('(Customer/#ID)[1]', 'varchar(20)')
-- Result: 123