Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally delete XML elements in XML field in SQL Server using T-SQL

I would like to conditionally remove elements in an XML field on SQL Server 2005. For example, I have the following data:

<stats>
    <stat date="2011-09-25 00:00:00" val="1"/>
    <stat date="2011-09-26 00:00:00" val="5"/>
    <stat date="2011-09-27 00:00:00" val="3"/>
</stats>

Using T-SQL, how can I remove the stat elements that have a date value older than, say, one day?

Theoretically, I guess the ideal solution can be expressed as:

UPDATE XML_TEST
    SET XML_DATA_FIELD.modify('delete (/stats/stat)')
    WHERE XML_DATA_FIELD.nodes('/stats/stat').value('@date',
    'datetime') < DATEADD(day, -1, GETDATE())

Which of course, does not work.

like image 728
DisposableCoder Avatar asked Apr 28 '26 05:04

DisposableCoder


1 Answers

This should achieve what you're looking for:

declare @testXml xml = '<stats>
    <stat date="2011-09-25 00:00:00" val="1"/>
    <stat date="2011-09-26 00:00:00" val="5"/>
    <stat date="2011-09-27 00:00:00" val="3"/>
</stats>'
,@yesterday varchar(20) = convert(varchar, dateadd(day, -1, getdate()), 120)

set @testXml.modify('delete //stat[@date < sql:variable("@yesterday")]')

Ew, string comparison...

like image 50
canon Avatar answered Apr 30 '26 20:04

canon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!