Re: How to read Value from XML String and Insert to a table
- From: "balajikkrishnan via SQLMonster.com" <u5178@uwe>
- Date: Tue, 12 May 2009 15:33:09 GMT
HI Plamen,
This works as expected. Can you explain us brief on the logic.
Also this will work only on SQL Server 2005 rite?
Why is this master..spt_values used?
Thanks in advance
Plamen Ratchev wrote:
Here is one method. Involves parsing XML, pivoting, and splitting
delimited list.
DECLARE @xmlMTPData XML;
SET @xmlMTPData =
N'<mtp>
<item>
<CName>Name</CName>
<CValue>Andrey</CValue>
</item>
<item>
<CName>Location</CName>
<CValue>Zurich</CValue>
</item>
<item>
<CName>Quantity</CName>
<CValue>500;200;300;600</CValue>
</item>
</mtp>';
SELECT n + 1 - LEN(REPLACE(LEFT(Quantity, n), ';', '')) AS id,
Name,
Location,
SUBSTRING(Quantity, n,
CHARINDEX(';',
Quantity + ';', n) - n) AS Quantity
FROM (
SELECT Name, Location, Quantity
FROM (
SELECT T.item.query('CName').value('.', 'VARCHAR(50)') AS cname,
T.item.query('CValue').value('.', 'VARCHAR(200)') AS cvalue
FROM @xmlMTPData.nodes('mtp/item') AS T(item)) AS X
PIVOT
(MAX(cvalue) FOR cname IN (Name, Location, Quantity)) AS P) AS D
JOIN (SELECT number
FROM master..spt_values
WHERE type = 'P'
AND number BETWEEN 1 AND 250) AS Nums(n)
ON SUBSTRING(';' + Quantity, n, 1) = ';'
AND n < LEN(Quantity) + 1;
/*
Results:
id Name Location Quantity
---- -------- ---------- ---------
1 Andrey Zurich 500
2 Andrey Zurich 200
3 Andrey Zurich 300
4 Andrey Zurich 600
*/
--
Message posted via http://www.sqlmonster.com
.
- Follow-Ups:
- Re: How to read Value from XML String and Insert to a table
- From: Plamen Ratchev
- Re: How to read Value from XML String and Insert to a table
- References:
- How to read Value from XML String and Insert to a table
- From: balajikkrishnan
- Re: How to read Value from XML String and Insert to a table
- From: Plamen Ratchev
- How to read Value from XML String and Insert to a table
- Prev by Date: Re: Change idendity property
- Next by Date: Re: GRANT VIEW SERVER STATE to Database Role
- Previous by thread: Re: How to read Value from XML String and Insert to a table
- Next by thread: Re: How to read Value from XML String and Insert to a table
- Index(es):