parsing multiple xml arrays in sql
Here's my setup: I am passing two arrays as XML into a SQL stored procedure.
These are:
<PhoneID Value=128/>
<PhoneID Value=129/>
<PhoneID Value=130/>
and
<AddressID Value=268/>
<AddressID Value=157/>
<AddressID Value=395/>
The Address
and Phone
ta开发者_如何学编程bles look like this (pseudo-code follows):
Phone:
BIGINT PhoneID
BIGINT PhoneNumber
SMALLINT AreaCode
INT Extension
Address:
BIGINT AddressID
NVARCHAR StreetAddress
NVARCHAR CountryName
NVARCHAR City
BIGINT Zip
My dilemma is this:
I need to walk through the passed in arrays in lock-step to return
ContactInfo:
BIGINT PhoneNumber
NVARCHAR StreetAddress
BIGINT ZipCode
i.e. I need to return one ContactInfo built from Phone where PhoneID = 128 and Address where AddressID = 268, and another where PhoneID = 129 and AddressID = 268, etc.
My big question is: How do I walk two xml arrays in lock-step in sql?
This is in SQL Server 2008 R2.
Thanks everyone :)
The only viable approach I see is trying to do this:
- parse/shred your XML arrays into temporary tables for phones and addresses
- those temporary tables have an
ID INT IDENTITY
defined - when inserting into a fresh temporary table with this INT IDENTITY, both sets of data will get consecutive numbering (1, 2, 3, 4......)
- you can then join the two temporary tables on their ID and should get your "lock-step" behavior:
So in code, this would look something like (mind you: your XML is invalid, too - the attribute values need to be in double quotes for this to work!):
DECLARE @phones XML = '<PhoneID Value="128"/><PhoneID Value="129"/><PhoneID Value="130"/>'
DECLARE @Addresses XML = '<AddressID Value="268"/><AddressID Value="157"/><AddressID Value="395"/>'
DECLARE @phoneTable TABLE (ID INT IDENTITY PRIMARY KEY, PhoneID INT)
DECLARE @AddressTable TABLE (ID INT IDENTITY PRIMARY KEY, AddressID INT)
INSERT INTO @phoneTable(PhoneID)
SELECT
PHID.value('(@Value)', 'int')
FROM
@phones.nodes('/PhoneID') AS PH(PHID)
INSERT INTO @AddressTable(AddressID)
SELECT
ADRID.value('(@Value)', 'int')
FROM
@addresses.nodes('/AddressID') AS AD(ADRID)
SELECT p.*, a.*
FROM @phoneTable p
INNER JOIN @addresstable a ON p.ID = a.ID
Does that work for you?? From here, you could then insert the data into your actual working tables and do any additional lookups or processing.
Turns out it's possible to in T-SQL, like so:
CREATE PROCEDURE [dbo].[XmlParsingProcedure]
@XmlArgs XML
AS
SELECT * FROM SomeTable
WHERE (s.XmlArgs IN (select x.XmlArgs.value('@Value','smallint') FROM @XmlArgs.nodes('//XmlArgs') as x(XmlArgs)))
However, intrinsic knowledge of the XML is required. The above implies the XML schema:
<XmlArgs Value="some value"/>
<XmlArgs Value="some other value"/>
<XmlArgs Value="yet another value"/>
where both, 'XmlArgs' and 'Value' are case sensitive.
精彩评论