kevin RemoveThis @teamstephens.com wrote:
> I have an XML column that contains multiple records and am looking for
> a way to get all of the values using a.value like query. Below is some
> TSQL that illustrates my question. Thanks for checking this out.
>
> -------------------------------------------------------------------------------------------------------------------------------
>
>
> Set NoCount ON
>
> If OBJECT_ID('tempdb..#TmpTest') is Not NULL
> Drop Table #TmpTest
> GO
>
> Create Table #TmpTest (TmpTestID int identity(1,1) Not NULL,Why XML
> NOT NULL)
>
> Insert into #TmpTest(Why) Values ('<Whys><Why
> fieldName="Prmr_Ad_Reason_1" fieldValue="" /><Why
> fieldName="Chd_Agent_Bank" fieldValue="0100" /><Why
> fieldName="Chd_Status_Reason_Code" fieldValue="05" /><Why
> fieldName="Chd_Portfolio_No" fieldValue="00001" /><Why
> fieldName="Chd_Del_No_Cycles" fieldValue="3" /><Why
> fieldName="Chd_Random_Digits" fieldValue="35" /><Why
> fieldName="Chd_External_Status" fieldValue="C" /><Why
> fieldName="Chd_Current_Balance" fieldValue="21529.2500" /><Why
> fieldName="Chd_Telephone_Number" fieldValue="04136647326" /></Whys>')
> Insert into #TmpTest(Why) Values ('<Whys><Why
> fieldName="Chd_Del_No_Cycles" fieldValue="2" /><Why
> fieldName="Chd_Del_No_Cycles" fieldValue="C" /></Whys>')
>
>
> --
> XxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXx
> -- This works great... but I need to be able do do this on a select on
> a table like below
> --
> XxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXx
> Declare @Test XML
>
> Select @test = (
> Select Why
> From #TmpTest ph
> Where TmpTestID = 1
> )
>
> SELECT Whys.Why.value('./@fieldName', 'varchar(100)') as fieldName,
> Whys.Why.value('./@fieldValue', 'varchar(7000)') as fieldValue
> FROM @test.nodes('/Whys/Why')
> Whys(Why)
> --
> XxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXx
> -- This query woks great but only pulls the first record within the
> Why element... I would like to see
> -- 8 records come back from this with a tmpTestID of 1 and 2 with a
> tmpTestID of 2
I think there should be nine not eight records for tmpTestID 1.
Here are two sample queries making use of the CROSS APPLY operator to
extract the records you are looking for:
SELECT Whys.Why.value('./@fieldName', 'varchar(100)') as fieldName,
Whys.Why.value('./@fieldValue', 'varchar(7000)') as fieldValue
FROM #TmpTest AS T CROSS APPLY T.Why.nodes('/Whys/Why') Whys(Why)
WHERE T.TmpTestID = 1
SELECT Whys.Why.value('./@fieldName', 'varchar(100)') as fieldName,
Whys.Why.value('./@fieldValue', 'varchar(7000)') as fieldValue
FROM #TmpTest AS T CROSS APPLY T.Why.nodes('/Whys/Why') Whys(Why)
WHERE T.TmpTestID = 2
--
Martin Honnen --- MVP XML
http://JavaScript.FAQTs.com/
>> Stay informed about: Simple XML column Query Question?