简体   繁体   中英

How to store and extract XML information from an nvarchar(max) type column, and use it in joins?

I have a column of type 'nvarchar(max)' that should now hold XML information instead of just a string.

Say: col1 has value 'abc' Now it has values, with additional info:

<el1>abc</el2>
<el2>someotherinfo</el2>

Storing the information to the column is fine, since it can still be pushed in as a string. However, extracting the same information and also using/replacing the same information 'abc' from this column that is being used in various other joins from other tables, is something I'm not able to figure out.

how can I also push in this information into abcd when it comes from another table's value 'abcd' without losing other information?

I am building an XML from the application side and updating it in a column of type nvarchar(). All the columns have been replaced to hold the XML, so the safe assumption is that the col1 only holds XML similar to that mentioned above. Just push the XML as is and it works fine. However, how should I extract the information to use it in joins?

How do I extract a particular element from this nvarchar() string to use it in a join?? Previously, this column 'Col1' was just used as a string, and a check was done like this:

where tablex.colx = table1.col1

or Update Table2 where

Once you cast the NVARCHAR data to the XML data type, you can use XML functions to get element/attribute values for joining to:

WITH xoutput AS (
  SELECT CONVERT(xml, t.nvarchar_column) AS col
    FROM YOUR_TABLE t)
SELECT x.*
  FROM TABLE x
  JOIN xoutput y ON y.col.value('(/path/to/your/element)[1]', 'int') = x.id

It won't be able to use indexes, because of the data type conversion...

Alternate version, using IN:

WITH xoutput AS (
   SELECT CONVERT(xml, t.nvarchar_column) AS col
     FROM YOUR_TABLE t)
SELECT x.*
  FROM TABLE x
 WHERE x.id IN (SELECT y.col.value('(/path/to/your/element)[1]', 'int')
                  FROM xoutput)

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