Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Remove string between two characters

I have a string such as this:

`a|b^c|d|e^f|g`

and I want to maintain the pipe delimiting, but remove the carrot sub-delimiting, only retaining the first value of that sub-delimiter.

The output result would be:

`a|b|d|e|g`

Is there a way I can do this with a simple SQL function?

like image 399
kunkel1 Avatar asked Mar 15 '16 16:03

kunkel1


2 Answers

Another option, using CHARINDEX, REPLACE and SUBSTRING:

DECLARE @OriginalString varchar(50) = 'a|b^c^d^e|f|g'

DECLARE @MyString varchar(50) = @OriginalString 

WHILE CHARINDEX('^', @MyString) > 0 
BEGIN
    SELECT @MyString = REPLACE(@MyString, 
                               SUBSTRING(@MyString, 
                                         CHARINDEX('^', @MyString), 
                                         CASE WHEN CHARINDEX('|', @MyString, CHARINDEX('^', @MyString)) > 0 THEN
                                            CHARINDEX('|', @MyString, CHARINDEX('^', @MyString)) - CHARINDEX('^', @MyString)
                                         ELSE
                                            LEN(@MyString)
                                         END
                                         )
                       , '')
END

SELECT @OriginalString As Original, @MyString As Final

Output:

Original              Final
a|b^c^d^e|f|g         a|b|f|g
like image 163
Zohar Peled Avatar answered Sep 28 '22 20:09

Zohar Peled


This expression will replace the first instance of caret up to the subsequent pipe (or end of string.) You can just run a loop until no more rows are updated or no more carets are found inside the function, etc.

case
    when charindex('^', s) > 0
    then stuff(
             s,
             charindex('^', s),
             charindex('|', s + '|', charindex('^', s) + 1) - charindex('^', s),
             ''
         )
    else s
end

Here's a loop you can adapt for a function definition:

declare @s varchar(30) = 'a|b^c^d|e|f^g|h^i';
declare @n int = charindex('^', @s);

while @n > 0
begin
    set @s = stuff(@s, @n, charindex('|', @s + '|', @n + 1) - @n, '');
    set @n = charindex('^', @s, @n + 1);
end
select @s;

A little bit of care needs to be taken for the trailing of the string where there won't be a final pipe separator. You can see I've handled that.

like image 22
shawnt00 Avatar answered Sep 28 '22 22:09

shawnt00