简体   繁体   中英

querying using two attributes in xml column

I have seen some examples querying using a single attribute but am puzzled on how to use 2 attributes.

<componentcache>
  <component Name="CALC_TODAYDATELONG" value="MONDAY, MAY 06, 2013" />
  <component Name="CALC_OFFICENAME" value="DEFAULT OFFICE" />
  <component Name="STAFFINFO_FULLNAME" value="LEE LEE, JR" />
  <component Name="PATINFO_FULLNAME" value="JAYNE H DOE" />
  <component Name="PATINFO_BIRTHDATE" value="11/07/1901" />
  <component Name="PATINFO_PATIENTNO" value="AG000003" />  
  <component Name="ENCOUNT_DXDESC1" value="ABC" />
  <component Name="ENCOUNT_DXDESC2" value="DEF" />
  <component Name="ENCOUNT_DXDESC3" value="HIJK" />
</componentcache>

SELECT DocumentStoreID, DocTemplateID, PersonID, Document from DocumentStore
WHERE DataCache.value('/componentcache/component...

I want to select the row(s) where Name like "ENCOUNT_DXDESC%" and value = 'DEF'

Try something like this using a CTE (Common Table Expression):

;WITH XmlDataValues AS
(
    SELECT 
        DocumentStoreID,
        CompName = XComp.value('@Name', 'varchar(50)'),
        CompValue = XComp.value('@value', 'varchar(50)')
    from 
        DocumentStore
    CROSS APPLY
        DataCache.nodes('/componentcache/component') XTbl(XComp)  
)   
SELECT * 
FROM XmlDataValues
WHERE CompName LIKE 'ENCOUNT%'
AND CompValue = 'DEF'

The CTE basically takes every row in DocumentStore and gets a list of all <component> XML nodes (as XML) and extracts Name and value attributes from those XML nodes. The CTE then surfaces this information like a relational table - with column names CompName and CompValue . You can easily select from the CTE and use normal T-SQL statements and conditions for that

Here's a method using XQuery:

SELECT DocumentStoreID, DocTemplateID, PersonID, Document from DocumentStore
WHERE DataCache.exist('/componentcache/component[contains(@Name, "ENCOUNT_DXDESC")][@value="DEF"]')=1

This will return all rows in your table which contain an XML document with a node that has a Name attribute containing "ENCOUNT_DXDESC" and a value attribute of "DEF"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM