使用分隔符拆分列

时间:2014-12-10 17:08:51

标签: sql sql-server

我的列中的值为AAA-BBB-CCCAAA-BBB-CCC-DDD

我只对分割和检索AAA BBB CCC感兴趣。

我尝试使用PARSENAME,但这会让人感到困惑。

3 个答案:

答案 0 :(得分:2)

SQL Fiddle

MS SQL Server 2008架构设置

CREATE TABLE Table1
    ([value] varchar(50))
;

INSERT INTO Table1
    ([value])
VALUES
    ('AAA-BBB-CCC'),
    ('AAA-BBB-CCC-DDD'),
    ('AAAAA-BBBB-CCCC'),
    ('AAAAA-BBBB-CCCCCC-DDD'),
    ('AAAAAA-BBB-CCC'),
    ('AAAAAAAA-BBBBBB-CCCCCC-DDD-EEEE')

;

查询1

SELECT replace(
          substring(value,1,(
               case when charindex('-',value,charindex('-',value,charindex('-',value)+1)+1) = 0 
                    then len(value)
                    else charindex('-',value,charindex('-',value,charindex('-',value)+1)+1)-1 end
          )),'-',' ')
FROM Table1

<强> Results

|               COLUMN_0 |
|------------------------|
|            AAA BBB CCC |
|            AAA BBB CCC |
|        AAAAA BBBB CCCC |
|      AAAAA BBBB CCCCCC |
|         AAAAAA BBB CCC |
| AAAAAAAA BBBBBB CCCCCC |

OR

SQL Fiddle

查询2

SELECT value,
       PARSENAME(replace(
          substring(value,1,(
               case when charindex('-',value,charindex('-',value,charindex('-',value)+1)+1) = 0 
                    then len(value)
                    else charindex('-',value,charindex('-',value,charindex('-',value)+1)+1)-1 end
          )),'-','.'),3) as '1st',
       PARSENAME(replace(
          substring(value,1,(
               case when charindex('-',value,charindex('-',value,charindex('-',value)+1)+1) = 0 
                    then len(value)
                    else charindex('-',value,charindex('-',value,charindex('-',value)+1)+1)-1 end
          )),'-','.'),2) as '2nd',
       PARSENAME(replace(
          substring(value,1,(
               case when charindex('-',value,charindex('-',value,charindex('-',value)+1)+1) = 0 
                    then len(value)
                    else charindex('-',value,charindex('-',value,charindex('-',value)+1)+1)-1 end
          )),'-','.'),1) as '3rd'
FROM Table1

<强> Results

|                           VALUE |      1ST |    2ND |    3RD |
|---------------------------------|----------|--------|--------|
|                     AAA-BBB-CCC |      AAA |    BBB |    CCC |
|                 AAA-BBB-CCC-DDD |      AAA |    BBB |    CCC |
|                 AAAAA-BBBB-CCCC |    AAAAA |   BBBB |   CCCC |
|           AAAAA-BBBB-CCCCCC-DDD |    AAAAA |   BBBB | CCCCCC |
|                  AAAAAA-BBB-CCC |   AAAAAA |    BBB |    CCC |
| AAAAAAAA-BBBBBB-CCCCCC-DDD-EEEE | AAAAAAAA | BBBBBB | CCCCCC |

答案 1 :(得分:1)

一种解决方案是使用替换功能,如下所示:

select replace(columnName, '-', ' ') as SplittedVal

如果只需要AAA BBB CCC并且值形成为3个字符空格3个字符空格3个字符(总共11个字符)则使用:

select left(replace(columnName, '-', ' '), 11)

答案 2 :(得分:0)

如果我理解正确,你的唯一目的是用空格替换-。如果是这样,只需使用REPLACE函数。

SELECT REPLACE('abcdefghicde','cde','xxx');
do

所以,您的代码将是

SELECT REPLACE('AAA-BBB-CCC','-',' ');
do