sql >> Database teknologi >  >> RDS >> Sqlserver

Opdel en lang kommastreng i en ny tabel med flere kolonner

Prøv dette

;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

For at indsætte i en anden tabel (eks:Detalje) prøv nedenfor

;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. ORA-28001:adgangskoden er udløbet, kan ikke rettes

  2. Er LAST_INSERT_ID() i en transaktion pålidelig?

  3. Sådan sletter du poster IKKE IN

  4. MySql 5.7 ORDER BY-klausul er ikke i GROUP BY-klausul og indeholder ikke-aggregeret kolonne