简体   繁体   中英

Convert ntext column to xml and get a node's value in SQL

I want to get a node 'RID' from this xml :

<ts:Status xmlns:ts="DistServices">
<RID>
5ec827e9-0429-4f5a-9d4b-16d3503ff07b
</RID>
<PIN>
5678
</PIN>
</ts:Status>

I am using the following query in SQL server 2012:

DECLARE @data xml  
DECLARE @RID varchar(256) 
select @data = CAST(CAST(Data AS text) AS XML) from message where index=1
select @data
SET @RID =  @data.value('(/ReplicationStatus/RID)[1]', 'varchar(256)' )  
SELECT @RID 

Here, Data is ntext. I casted it twice from ntext to text and then to xml. Now, I am getting @data in xml format. But RID returned is always null. Can someone help me with this?

You could try after converting ntext data to xml :

DECLARE @DATA XML = '<ts:Status xmlns:ts="DistServices">
<RID>
5ec827e9-0429-4f5a-9d4b-16d3503ff07b
</RID>
<PIN>
5678
</PIN>
</ts:Status>'

SELECT 
       a.value('./RID[1]', 'NVARCHAR(MAX)') [RID],
       a.value('./PIN[1]', 'NVARCHAR(MAX)') [PIN]
       FROM @DATA.nodes ('*') as split(a)

Result :

RID                                   PIN
5ec827e9-0429-4f5a-9d4b-16d3503ff07b  5678

Note : IMPORTANT ! ntext, text, and image data types will be removed in a future version of SQL Server. Avoid using these data types in new development work, and plan to modify applications that currently use them. Use nvarchar(max), varchar(max), and varbinary(max) instead.

Read https://docs.microsoft.com/en-us/sql/t-sql/data-types/ntext-text-and-image-transact-sql

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