2013-02-28 59 views
2

如何將字符串轉換爲XML數據類型,這樣我就可以查詢到的數據爲XML之前,將字符串轉換爲XML數據類型:在查詢T-SQL

例如(感謝「mellamokb智者」誰爲此提供的原始SQL)

下面的代碼工作正常,如果的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類型我得到一個錯誤,儘管我m將字符串轉換爲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) 

回答

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