sql >> データベース >  >> RDS >> Sqlserver

1つの長いコンマ文字列を複数列の新しいテーブルに分割します

    これを試してください

    ;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デモ

    または

    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
    

    別のテーブルに挿入するには (例:詳細)以下をお試しください

    ;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. ORACLE SQL select Distinctは、重複を削除しません

    2. これは安全で強力な入力サニタイズ機能ですか?

    3. QueryDSLでのケースビルダー式の合計

    4. C#を使用してMySqlに日付を挿入します