Transact SQL :- XQuery – Union – Basic Study

Background

Wanted to hopefully do a better job showing how to use XPath or clause.

Basket

basket.png

Query

Get Apples ( /item/type => apple )

SQL


select
          [item] = x.y.query('.')
        , [parent] = x.y.query('..')

from   @basket.nodes
        (
            '
             /basket/item/type[.="apple"]
            '
        ) as  x(y)  

Output

xquery.type.apple

Get Pears ( /item/type => pear )

SQL


select
          [item] = x.y.query('.')
        , [parent] = x.y.query('..')

from   @basket.nodes
        (
            '
             /basket/item/type[.="pear"]
            '
        ) as  x(y) 

Output

xquery.type.pear.PNG

Get Apples or Pears ( /item/type => apple or pear ) => Use XPath Union

Outline

  1. Use XPath Union
    • Each XPath is separated with hyphen ( | )

SQL


select
          [item] = x.y.query('.')
        , [parent] = x.y.query('..')

from   @basket.nodes
        (
            '
                  /basket/item/type[.="pear"]
                | /basket/item/type[.="pear"]
            '
        ) as  x(y) 

Output

Text


Msg 9335, Level 16, State 1, Line 90
XQuery [nodes()]: The XQuery syntax 'union' is not supported.

Image

xquery.type.appleorpear.union

Get Apples or Pears ( /item/type => apple or pear ) => Use XPath Union

Outline

  1. Use XPath Union
    • Each XPath is separated with comma ( , )

SQL


select
          [item] = x.y.query('.')
        , [parent] = x.y.query('..')

from   @basket.nodes
        (
            '
                  /basket/item/type[.="pear"]
                , /basket/item/type[.="pear"]
            '
        ) as  x(y) 

Output

Image

xquery.type.appleorpear.union-transactSQL

 

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s