在T-SQL中查询之前将字符串转换为XML数据类型

时间:2013-02-28 13:07:14

标签: sql-server xml tsql

如何将字符串转换为XML数据类型,以便我可以将数据作为XML查询:

例如(感谢为此提供原始SQL的“mellamokb the Wise”)

如果xmlstring属于XML类型,则下面的代码可以正常工作(参见DEMO

select id, name
from Data
cross apply (
  select Destination.value('data(@Name)', 'varchar(50)') as name
  from [xmlstring].nodes('/Holidays/Summer/Regions/Destinations/Destination') D(Destination)
) Destinations(Name)

但是,如果xmlString的类型为varchar,即使我将字符串转换为XML(DEMO),我也会收到错误:

select id, name
from Data
  cross apply (
  select Destination.value('data(@Name)', 'varchar(50)') as name
  from CONVERT(xml,[xmlstring]).nodes('/Holidays/Summer/Regions/Destinations/Destination') D(Destination)
) Destinations(Name)

1 个答案:

答案 0 :(得分:4)

你可以在一次额外交叉申请中进行投射。

select id,
       T.N.value('@Name', 'varchar(50)') as name
from Data
cross apply (select cast(xmlstring as xml)) as X(X)
cross apply X.X.nodes('/Holidays/Summer/Regions/Destinations/Destination') T(N)

SQL Fiddle

转换为XML可能会出现性能问题。请查看this answerthis answer