Reputation: 75
I'm trying to extract an XML value from a SQL Server column and put it into a SQL statement. My problem is that the documentation I've found doesn't explain how to do this if there are spaces or ""
in the XML path.
I'm trying to extract the value
property in the XML shown here (there is no namespace in the XML). The SQL Server column is called Settings
:
<properties>
<settings hwid="stream:0.0.0">
<setting typeid="78622C19-58AE-40D4-8EEA-17351F4273B6">
<name>Codec</name>
<value>4</value>
</setting>
</settings>
</properties>
Upvotes: 1
Views: 220
Reputation: 5102
You can use OPENXML
to retrieve data from xml, first create procedure like this:
CREATE PROCEDURE GetXmlValueProc
@xml NVARCHAR(max)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @hdoc INT;
EXEC sp_xml_preparedocument @hdoc OUTPUT, @xml;
DECLARE @Result NVARCHAR(50);
SELECT value
FROM
OPENXML(@hdoc, '/properties/settings/setting', 2)
WITH
(
value VARCHAR(100)
);
EXEC sp_xml_removedocument @hdoc;
END
GO
And call procedure in this way:
DECLARE @xml NVARCHAR(MAX)='<properties><settings hwid="stream:0.0.0"><setting typeid="78622C19-58AE-40D4-8EEA-17351F4273B6"><name>Codec</name><value>4</value></setting></settings></properties>'
EXEC dbo.GetXmlValueProc @xml
Even you can make procedure more generic and pass the xml path to get data.
Upvotes: 1
Reputation: 72415
I don't see any spaces in your XML. If you mean the various attributes, such as hwid
, those are parsed separately from the node names. You can select those by prefacing with @
.
I assume the type of the value
node is int
, if not you can change it below:
SELECT
t.Settings.value('(/properties/settings/setting/value)[1]', 'int'),
t.Settings.value('(/properties/settings/setting/@typeid)[1]', 'uniqueidentifier'),
t.Settings.value('(/properties/settings/@hwid)[1]', 'nvarchar(max)')
FROM myTable t
For reference, if you ever did have a node with a space in it: it would be encoded  
and a double-quote as "
Upvotes: 0