sql >> Databáze >  >> RDS >> Sqlserver

Rozdělte jeden dlouhý řetězec čárky do nové tabulky s více sloupci

Zkuste toto

;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

Ukázka SQLFiddle

NEBO

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

Chcete-li vložit do jiné tabulky (např.:Detail) zkuste níže

;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. PHP krátké generování jedinečného ID pomocí auto_increment?

  2. SQL SERVER 2008 tipy JOIN

  3. Jak vybrat název domény z e-mailové adresy

  4. SQL – připojte se k propojenému serveru pomocí pojmenované instance