将长字符串拆分为列和行

时间:2015-04-18 04:00:44

标签: sql sql-server sql-server-2012

如何分隔长字符串并将它们分成三列。列由|分隔,行由,

分隔

例如字符串

Toronto|Ontario|Canada,Dallas|Texas|USA,New York|New York|USA,Windsor|Ontario|Canada

我有一个有5列的表,3列是城市,州和国家。

我想将它们分开并将它们分类

Continent          City            State        Country  Added

                    Toronto      Ontario     Canada

                    Dallas        Texas       USA

                    New York   New York       USA

3 个答案:

答案 0 :(得分:1)

您可以采用这种标准方式。首先将字符串拆分为行,然后将每行拆分为列:

declare @s nvarchar(max) = 'a|b|c,d|e|f'

;with rows as(
  select x.t.value('.', 'nvarchar(max)') r
  from (select cast('<x>'+replace(replace(@s,'|','.'),',','</x><x>')+'</x>' as xml) d) t
  cross apply t.d.nodes('/x') x(t))

  select parsename(r, 3) as col1,
         parsename(r, 2) as col2,
         parsename(r, 1) as col3
  from rows

输出:

col1    col2    col3
a       b       c
d       e       f

小提琴http://sqlfiddle.com/#!6/9eecb/4220

答案 1 :(得分:0)

检查此示例。

DECLARE @string VARCHAR(500)  = 'Toronto|Ontario|Canada,Dallas|Texas|USA,New York|New York|USA,Windsor|Ontario|Canada'

SELECT 
PARSENAME(REPLACE(Data, '|', '.'), 1) AS COUNTRY,
PARSENAME(REPLACE(Data, '|', '.'), 2)  AS STATE,
PARSENAME(REPLACE(Data, '|', '.'), 3)  
CITY
FROM
(SELECT 
     Split.a.value('.', 'VARCHAR(500)') AS Data  
 FROM  
 (
     SELECT
          CAST ('<M>' + REPLACE(@string, ',', '</M><M>') + '</M>' AS XML) AS Data       
 ) AS A  
 CROSS APPLY Data.nodes ('/M') AS Split(a)
 ) b

会给出这个答案。

COUNTRY     STATE       CITY        
Canada      Ontario     Toronto
USA         Texas       Dallas
USA         New York    New York
Canada      Ontario     Windsor

答案 2 :(得分:0)

嗨,请使用此< - strong>

create table myTable (Continent varchar(30),City varchar(30),State 
varchar(30),Country varchar(30),Added varchar(30))

declare @input varchar(200)
set @input = 'Toronto|Ontario|Canada,Dallas|Texas|USA,New York|New 
              York|USA,Windsor|Ontario|Canada'
Declare @Qry Varchar(7000)      
Set @Qry = ''        
Select @Qry = @Qry + ' Insert into myTable (City,State ,Country) '    
Select @Qry = @Qry +  Replace( 'Select ''' + 
       Replace(Replace(Replace(Replace(@input,CHAR(9),''),' 
       ',''),CHAR(10),''),CHAR(13),'') , ',',''' Union Select ''') + ''''           
set @Qry = replace(@Qry,'|',''',''')
Exec (@Qry) 

select * from myTable