sql >> Databasteknik >  >> RDS >> Sqlserver

Dela en lång kommasträng i en ny tabell med flera kolumner

Prova detta

;WITH Split_Fields (Field, xmlfields)
AS
(
    SELECT Field1 AS Field,
    CONVERT(XML,'<Fields><field>'  
    + REPLACE(Field1,',', '</field><field>') + '</field></Fields>') AS xmlfields
      FROM Table1
)

 SELECT Field,      
 xmlfields.value('/Fields[1]/field[1]','varchar(100)') AS Field1,    
 xmlfields.value('/Fields[1]/field[2]','varchar(100)') AS Field2,
 xmlfields.value('/Fields[1]/field[3]','varchar(100)') AS Field3,    
 xmlfields.value('/Fields[1]/field[4]','varchar(100)') AS Field4,
 xmlfields.value('/Fields[1]/field[5]','varchar(100)') AS Field5
 FROM Split_Fields

SQLFiddle Demo

ELLER

SELECT Field,
xmlfields.value('/Fields[1]/field[1]','varchar(100)') AS Field1, 
xmlfields.value('/Fields[1]/field[2]','varchar(100)') AS Field2, 
xmlfields.value('/Fields[1]/field[3]','varchar(100)') AS Field3, 
xmlfields.value('/Fields[1]/field[4]','varchar(100)') AS Field4, 
xmlfields.value('/Fields[1]/field[5]','varchar(100)') AS Field5 
FROM 
(
SELECT 
Field1 AS Field
,CONVERT(XML,'<Fields><field>' + REPLACE(Field1,',', '</field><field>') + '</field></Fields>') AS xmlfields 
FROM Table1
) Split_Fields

För att infoga i en annan tabell (ex:Detalj) försök nedan

;WITH Split_Fields (Field, xmlfields)
AS
( 
SELECT 
Field1 AS Field
,CONVERT(XML,'<Fields><field>' + REPLACE(Field1,',', '</field><field>') + '</field></Fields>') AS xmlfields 
FROM Table1
) 

INSERT INTO Detail
SELECT 
xmlfields.value('/Fields[1]/field[1]','varchar(100)') AS Field1, 
xmlfields.value('/Fields[1]/field[2]','varchar(100)') AS Field2, 
xmlfields.value('/Fields[1]/field[3]','varchar(100)') AS Field3, 
xmlfields.value('/Fields[1]/field[4]','varchar(100)') AS Field4, 
xmlfields.value('/Fields[1]/field[5]','varchar(100)') AS Field5 
FROM Split_Fields


  1. Postgresl select count(*) tidskrävande

  2. MySQL:Snabb uppdelning av typerna av kopplingar

  3. Radera selektivt mestadels duplicerade poster från MySQL

  4. ORDER BY-funktionen fungerar inte i Oracle