I have a column of ntext data type and NOT XML. It stores all xml data. I need to get records based on xml node value. =>input value is CpsiaId = 456 and should return all records which has this value in the xml
I tried select * from tableName
where convert(xml,column_name).value('data((/root/ProductInformation/CPSIA/CpsiaDetails/Item/CpsiaId)[1])','int') = 456
but it didn't work....any ideas or other way of getting the records based xml node value.
Sample Xml:
<root>
<ProductInformation>
<Name> Truck with Battery Charger</Name>
<Description>Fr.</Description>
<CPSIA>
<CpsiaDetails>
<Item>
<CpsiaId>456</CpsiaId>
<CpsiaMessage>waring</CpsiaMessage>
</Item>
<Item>
<CpsiaId>236</CpsiaId>
<CpsiaMessage>to health</CpsiaMessage>
</Item>
</CpsiaDetails>
</CPSIA>
</ProductInformation>
</root>
convert(xml,column_name).exist('/root/ProductInformation/CPSIA/CpsiaDetails/Item[CpsiaId=456]') = 1
This works, and you can replace the constant (456
) with an sql:variable()
if you need a dynamic value, like so (assuming a numeric variable @i
):
'/root/ProductInformation/CPSIA/CpsiaDetails/Item[CpsiaId=sql:variable("@i")]'
Edit:
Sample code as requested:
DECLARE @t nvarchar(MAX);
SET @t = '<root>
<ProductInformation>
<Name> Truck with Battery Charger</Name>
<Description>Fr.</Description>
<CPSIA>
<CpsiaDetails>
<Item>
<CpsiaId>456</CpsiaId>
<CpsiaMessage>waring</CpsiaMessage>
</Item>
<Item>
<CpsiaId>236</CpsiaId>
<CpsiaMessage>to health</CpsiaMessage>
</Item>
</CpsiaDetails>
</CPSIA>
</ProductInformation>
</root>'
DECLARE @i int;
SET @i = 456;
SELECT convert(xml,@t).exist('/root/ProductInformation/CPSIA/CpsiaDetails/Item[CpsiaId=sql:variable("@i")]')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With