Consider the following simple XML:
<xml>
<customer name="Max">
<email address="[email protected]" />
</customer>
<customer name="Erik">
<email address="[email protected]" />
</customer>
<customer name="Brent">
<email address="brentcom" />
</customer>
</xml>
I want to get a list of <Customer>
sequences where the address
attribute of the <email>
item does not contain an @
.
So, I want output that looks like:
<customer name="Brent">
<email address="brentcom" />
</customer>
mcve:
DECLARE @x XML = '<xml>
<customer name="Max"><email address="[email protected]" /></customer>
<customer name="Erik"><email address="[email protected]" /></customer>
<customer name="Brent"><email address="brentcom" /></customer>
</xml>';
This query:
SELECT WithValidEmail = @x.query('/xml/customer/email[contains(@address, "@")]')
, WithInvalidEmail = @x.query('/xml/customer/email[contains(@address, "@")] = False');
Returns:
╔═══════════════════════════════════════╦══════════════════╗
║ WithValidEmail ║ WithInvalidEmail ║
╠═══════════════════════════════════════╬══════════════════╣
║ <email address="[email protected]" /> ║ ║
║ <email address="[email protected]" /> ║ false ║
╚═══════════════════════════════════════╩══════════════════╝
This query:
SELECT WithInValidEmail = @x.query('/xml/customer/email')
WHERE @x.exist('/xml/customer/email[contains(@address, "@")]') = 0;
Returns:
╔══════════════════╗
║ WithInValidEmail ║
╚══════════════════╝
(no results)
The WHERE
clause in the query above is eliminating the entire set of XML because at least a single sequence exists where the email address contains an "@" sign.