How would I remove part of string before and after specific characters

时间:2017-06-09 12:44:24

标签: sql tsql

I am having a bit of an issue separating strings that contain multiple special characters.

enter image description here

I wish to separate the colours and not bring any of the special characters, I have been playing around with Charindex but it does not work well.

eg:

SELECT [Color combo]
  ,left([Color combo], CHARINDEX('.'  , replace([Color combo]) - 1)   AS [Primary]

FROM [test].[dbo].[Palate]

This errors out as when it hits line 3 with the"/" is there a way to filter multiple special characters?

1 个答案:

答案 0 :(得分:0)

如果我理解,那应该回答你的问题:

declare @T table (Id INT , Color_combo varchar(500) );
insert into @t values (1,'Pink.Blue') , (2,'Orange.White') , (3,'Yellow.Orange') , (4,'Red/Green') , (5,':Green.Purple\');

SELECT
        Id,
        Color_combo,
        LEFT(Color_combo, CASE WHEN CHARINDEX('.', Color_combo, 0) > 0
                               THEN CHARINDEX('.', Color_combo, 0) - 1
                               ELSE
                               CHARINDEX('/', Color_combo, 0) - 1
                          END)  AS [Primary],
        RIGHT(Color_combo, LEN(color_combo) - (CASE WHEN CHARINDEX('.', Color_combo, 0) > 0
                                THEN CHARINDEX('.', Color_combo, 0)
                                ELSE
                                CHARINDEX('/', Color_combo, 0)
                           END)) AS [Secondary]
FROM    @T;

Demo