Converting comma delimited string to multiple columns in sql server

后端 未结 4 944
借酒劲吻你
借酒劲吻你 2020-12-22 03:49

I want to extract specific strings separated by a comma and parse across the specific columns in SQL server 2008. The table structure in SQL server is as follows:

         


        
4条回答
  •  死守一世寂寞
    2020-12-22 04:29

    You can see this working on SQL Fiddle: http://sqlfiddle.com/#!3/8c3ee/32

    Here's the meat of it:

    with parsed as (
      select
      commasepa,
      root.value('(/root/s/col[@name="X"])[1]', 'varchar(20)') as X,
      root.value('(/root/s/col[@name="Y"])[1]', 'varchar(20)') as Y,
      root.value('(/root/s/col[@name="Z"])[1]', 'varchar(20)') as Z,
      root.value('(/root/s/col[@name="A"])[1]', 'varchar(20)') as A,
      root.value('(/root/s/col[@name="B"])[1]', 'varchar(20)') as B,
      root.value('(/root/s/col[@name="C"])[1]', 'varchar(20)') as C,
      root.value('(/root/s/col[@name="D"])[1]', 'varchar(20)') as D
    FROM
    (
    select
       commasepa,
       CONVERT(xml,''),',','1
     
     
      2
     
      ....
    
    

    Once I have the string in that format, I then use the xquery options that SQL Server 2005 (and up) support, which is the .value('(/root/s/col[@name="X"])[1]', 'varchar(20)') part. I select each of the potential columns individually, so they are normalized and populated when available. With that normalized format, I define the result set with a Common Table Expression (CTE) that I called 'parsed'. This CTE is then joined back in the update statement, so that the values can be populated in the original table.

提交回复
热议问题