1

I have to split one column (pipe delimited) into new columns.

Ex: column 1: Data|7-8|5

it should be split into

col2          col3         col4
Data          7-8          5

Please help me to solve this.

4

4 に答える 4

1

これで遊んでください。少し冗長ですが、操作のすべてのステップを示しています。フォローアップの質問がある場合は、お気軽にお尋ねください。

DECLARE @t table (
   piped varchar(50)
)

INSERT INTO @t (piped)
  VALUES ('pipe|delimited|values')
       , ('a|b|c');

; WITH x AS (
  SELECT piped
       , CharIndex('|', piped) As first_pipe
  FROM   @t
)
, y AS (
  SELECT piped
       , first_pipe
       , CharIndex('|', piped, first_pipe + 1) As second_pipe
       , SubString(piped, 0, first_pipe) As first_element
  FROM   x
)
, z AS (
  SELECT piped
       , first_pipe
       , second_pipe
       , first_element
       , SubString(piped, first_pipe  + 1, second_pipe - first_pipe - 1) As second_element
       , SubString(piped, second_pipe + 1, Len(piped) - second_pipe) As third_element
  FROM   y
)
SELECT *
FROM   z
于 2013-10-30T16:53:13.860 に答える
0

おそらくこれよりも何百もの良い方法がありますが、

declare @string as varchar(100)
set @string = 'Data|7-8|5'
select left(@string,CHARINDEX('|',@string,0) -1) as one, 
left(substring(@string,CHARINDEX('|',@string,0)+1,100),CHARINDEX('|',substring(@string,CHARINDEX('|',@string,0)+1,100),0) -1) as two,
reverse(left(reverse(@string),CHARINDEX('|',reverse(@string),0) -1)) as three
于 2013-10-30T17:01:51.347 に答える
0

この種の問題に対する私のお気に入りのアプローチの 1 つは、XML データ型を使用することです。私はそれのパフォーマンスについてあまり知りませんが、それは仕事をします.

DECLARE @line VARCHAR(MAX);
DECLARE @x xml;

/* example data */
SET @line = 'Data|7-8|5';


/* replace the delimeter with closing and opening tags,
   and wrap the line with opening and closing tags as well */
SET @x = Cast(
        '<field>'
        + replace(@line, '|', '</field><field>')
        + '</field>' AS XML);


/* query the nodes based on index */
SELECT
    @x.query('field[1]').value('.','VarChar(10)')   Col1
    ,@x.query('field[2]').value('.','VarChar(10)')  Col2
    ,@x.query('field[3]').value('.','Int')          Col3
于 2013-10-30T18:46:38.357 に答える