Converting comma delimited string to multiple columns in sql server

后端 未结 4 924
借酒劲吻你
借酒劲吻你 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

    DECLARE @SAMP TABLE
    (
      COMMASEPA VARCHAR(255),
      X VARCHAR(10),
      Y VARCHAR(10),
      Z VARCHAR(10),
      A VARCHAR(10),
      B VARCHAR(10),
      C VARCHAR(10),
      D VARCHAR(10)
    )
    INSERT INTO @SAMP VALUES
    ('X=1,Y=2,Z=3',null,null,null,null,null,null,null),
    ('X=3,Y=4,Z=5,A=6',null,null,null,null,null,null,null),
    ('X=1,Y=2,Z=3,A=5,B=6,C=7,D=8',null,null,null,null,null,null,null)
    
    update S set
      X = case when P.X > 3 then substring(T.COMMASEPA, P.X, charindex(',', T.COMMASEPA, P.X) - P.X) end,
      Y = case when P.Y > 3 then substring(T.COMMASEPA, P.Y, charindex(',', T.COMMASEPA, P.Y) - P.Y) end,
      Z = case when P.C > 3 then substring(T.COMMASEPA, P.Z, charindex(',', T.COMMASEPA, P.Z) - P.Z) end,
      A = case when P.A > 3 then substring(T.COMMASEPA, P.A, charindex(',', T.COMMASEPA, P.A) - P.A) end,
      B = case when P.B > 3 then substring(T.COMMASEPA, P.B, charindex(',', T.COMMASEPA, P.B) - P.B) end,
      C = case when P.C > 3 then substring(T.COMMASEPA, P.C, charindex(',', T.COMMASEPA, P.C) - P.C) end,
      D = case when P.D > 3 then substring(T.COMMASEPA, P.D, charindex(',', T.COMMASEPA, P.D) - P.D) end
    from @SAMP as S
      cross apply (select ','+S.COMMASEPA+',') as T(COMMASEPA)
      cross apply (select charindex(',X=', T.COMMASEPA)+3 as X,
                          charindex(',Y=', T.COMMASEPA)+3 as Y,
                          charindex(',Z=', T.COMMASEPA)+3 as Z,
                          charindex(',A=', T.COMMASEPA)+3 as A,
                          charindex(',B=', T.COMMASEPA)+3 as B,
                          charindex(',C=', T.COMMASEPA)+3 as C,
                          charindex(',D=', T.COMMASEPA)+3 as D) as P
    

提交回复
热议问题