Select SQL Query to get xml node values from ntext column? - sql

I want to get one xml node value from NTEXT column which contains xml based on where clause quering on another xml node value.
RDBMS Type: Microsoft SQL Server T-SQL
Here: I want to get Code node value based on StoreId where clause value. How do I get it?
Input: 100
Output:ABCDE
For example:
<root>
<StoreProfile>
<General>
<StoreId>100</StoreId>
<Code>ABCDE</Code>
</General>
</StoreProfile>
</root>

If you are using SQL Server 2005 or 2008 you can use XQuery like so:
For more on XQuery see XQuery Language Reference
DECLARE #storeId INT
SET #storeId = 100
CREATE TABLE #TestTable
(
xmlColumn NTEXT
)
INSERT INTO #TestTable (xmlColumn) Values('<root><StoreProfile><General><StoreId>100</StoreId><Code>ABCDE</Code></General></StoreProfile></root>')
INSERT INTO #TestTable (xmlColumn) Values('<root><StoreProfile><General><StoreId>200</StoreId><Code>FGHIJ</Code></General></StoreProfile></root>')
SELECT
StoreProfile.value('Code[1]', 'nvarchar(10)') as Code
FROM #TestTable
CROSS APPLY (SELECT CAST(xmlColumn AS XML)) AS A(B)
CROSS APPLY A.B.nodes('//root/StoreProfile/General[StoreId = sql:variable("#storeId")]') AS StoreProfiles(StoreProfile)
DROP TABLE #TestTable

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;

Easiest way to query a SQL Server 2008 R2 XML data type?

I need to get a node value in an XML data type column.
<CustomContentData>
<prpIsRSSFeed>false</prpIsRSSFeed>
</CustomContentData>
How is this done in SQL Server?
The column name is ClassXML
Use XQuery, a simple example with your data would be:
DECLARE #T TABLE (ClassXML XML);
INSERT #T (ClassXML)
VALUES ('<CustomContentData>
<prpIsRSSFeed>false</prpIsRSSFeed>
</CustomContentData>');
SELECT t.ClassXML.value('CustomContentData[1]/prpIsRSSFeed[1]', 'VARCHAR(5)')
FROM #T AS t;
If the column is already XML data type in SQL Server, then the code below should work by using the value function with XPATH. If it's stored as a varchar, you'd just need to replace ClassXML.value with CONVERT(XML, ClassXML).value. Hope this helps!
DECLARE #Data TABLE (ClassXML XML)
INSERT #Data VALUES ('<CustomContentData><prpIsRSSFeed>false</prpIsRSSFeed></CustomContentData>')
SELECT
CONVERT(BIT, CASE WHEN ClassXML.value ('(/CustomContentData/prpIsRSSFeed)[1]',
'VARCHAR(50)') = 'true' THEN 1 ELSE 0 END) AS IsRssFeed
FROM #Data
Yields output
IsRssFeed
---------
0

How to read column values from xmlstring using forxml clause

In our database table, columns are stored as an xml string, which is shown below.
<DocumentElement>
<PartInfo>
<ID>0</ID>
<PartNo>0</PartNo>
<SerialNo>1</SerialNo>
<Parameter>0</Parameter>
<InstalledDate>2013-01-15T00:00:00+05:30</InstalledDate>
<InstalledTill>2013-01-25T00:00:00+05:30</InstalledTill>
</PartInfo>
</DocumentElement>
I want to get column values of this string. For example I have to get the value 2013-01-15T00:00:00+05 of Installed Date column. How can I obtain this using forxml clause?
Assuming SQL-Server you can use something like this:
DECLARE #T TABLE (X XML);
INSERT #T VALUES ('<DocumentElement>
<PartInfo>
<ID>0</ID>
<PartNo>0</PartNo>
<SerialNo>1</SerialNo>
<Parameter>0</Parameter>
<InstalledDate>2013-01-15T00:00:00+05:30</InstalledDate>
<InstalledTill>2013-01-25T00:00:00+05:30</InstalledTill>
</PartInfo>
</DocumentElement>');
SELECT InstalledDate = X.value('/DocumentElement[1]/PartInfo[1]/InstalledDate[1]', 'DATETIME')
FROM #T;
If you could have multiple PartInfo nodes within DocumentElement then you'll need to use CROSS APPLY .. nodes to get all the InstalledDates
SELECT InstalledDate = PartInfo.value('InstalledDate[1]', 'DATETIME')
FROM #T
CROSS APPLY X.nodes('/DocumentElement/PartInfo') p (PartInfo);

how to get values inside an xml column, when it's of type nvarchar

My question is similar to this one: Choose a XML node in SQL Server based on max value of a child element
except that my column is NOT of type XML, it's of type nvarchar(max).
I want to extract the XML node values from a column that looks like this:
<Data>
<el1>1234</el1>
<el2>Something</el2>
</Data>
How can I extract the values '1234' and 'Something' ?
doing a convert and using the col.nodes is not working.
CONVERT(XML, table1.col1).value('(/Data/el1)[1]','int') as 'xcol1',
After that, I would like to do a compare value of el1 (1234) with another column, and update update el1 as is. Right now I'm trying to just rebuild the XML when passing the update:
ie
Update table set col1 ='<Data><el1>'+#col2+'</el1><el2>???</el2>
You've got to tell SQL Server the number of the node you're after, like:
(/Data/el1)[1]
^^^
Full example:
declare #t table (id int, col1 varchar(max))
insert #t values (1, '<Data><el1>1234</el1><el2>Something</el2></Data>')
select CAST(col1 as xml).value('(/Data/el1)[1]', 'int')
from #t
-->
1234
SQL Server provides a modify function to change XML columns. But I think you can only use it on columns with the xml type. Here's an example:
declare #q table (id int, col1 xml)
insert #q values (1, '<Data><el1>1234</el1><el2>Something</el2></Data>')
update #q
set col1.modify('replace value of (/Data/el1/text())[1] with "5678"')
select *
from #q
-->
<Data><el1>5678</el1><el2>Something</el2></Data>
At the end of the day, SQL Server's XML support makes simple things very hard. If you value maintainability, you're better off processing XML on the client side.

Serializing Hashset contents to a SQL table

I have a hashset that I want to serialize to a SQL Server table. When serialized hashset looks like this...
<InstallerContactIds>
<int>153771</int>
<int>209572</int>
</InstallerContactIds>
I am using the following to insert the XML into the table...
INSERT INTO dbo.cv_AssessorActionPlanInstallers
SELECT #AssessorActionPlanId, InstallerId
From OPENXML (#XmlDocumentHandle, 'AssessorActionPlan/InstallerContactIds', 2)
With
(
InstallerId int 'int'
)
However, I only get the first id inserted into the table. Is it possible to insert all ids in this case?
I am using SQL Server 2005
You didn't specify what version of SQL you are using, but if you are on 2005 or newer, you can use the new XML data type.
declare #xml xml
select #xml = '
<InstallerContactIds>
<int>153771</int>
<int>209572</int>
</InstallerContactIds>'
select
x.i.value('.', 'int')
from
#xml.nodes('/InstallerContactIds/int') as x(i)
If you are stuck using OpenXML, it should work if you do this:
INSERT INTO dbo.cv_AssessorActionPlanInstallers
SELECT #AssessorActionPlanId, InstallerId
From OPENXML (#XmlDocumentHandle, 'AssessorActionPlan/InstallerContactIds/int', 2)
With
(
InstallerId int '.'
)