-1

I have string separated by semicolons. There are some sub-strings which contains specific character like pipe |.

How to remove those sub-string using SQL Server?

Example:

1,abc;1,abc|1,def;1,abc|2,def;1,abc|3,def;1,abc|4,def;1,abc|5,def;1,abc|6,def;2,abc;2,abc|7,def;2,abc|7,def|1,xyz;2,abc|8,def

Result should be - 1,abc;2,abc;....

3 Answers3

0
SELECT REPLACE('1,abc;1,abc|1,def;1,abc|2,def;1,abc|3,def;1,abc|4,def;1,abc|5,def;1,abc|6,def;2,abc;2,abc|7,def;2,abc|7,def|1,xyz;2,abc|8,def','|','')
Raj
  • 10,653
  • 2
  • 45
  • 52
0

Create a function to split your string. Like the one in this post:

CREATE FUNCTION [dbo].[SDF_SplitString]
(
    @sString nvarchar(2048),
    @cDelimiter nchar(1)
)
RETURNS @tParts TABLE ( part nvarchar(2048) )
AS
BEGIN
    if @sString is null return
    declare @iStart int,
            @iPos int
    if substring( @sString, 1, 1 ) = @cDelimiter 
    begin
        set @iStart = 2
        insert into @tParts
        values( null )
    end
    else 
        set @iStart = 1
    while 1=1
    begin
        set @iPos = charindex( @cDelimiter, @sString, @iStart )
        if @iPos = 0
            set @iPos = len( @sString )+1
        if @iPos - @iStart > 0          
            insert into @tParts
            values  ( substring( @sString, @iStart, @iPos-@iStart ))
        else
            insert into @tParts
            values( null )
        set @iStart = @iPos+1
        if @iStart > len( @sString ) 
            break
    end
    RETURN

END

Then you'll have to remove the values from the returned table that contain the pipe '|' or you just select the values out of the returned table that don't contain any pipe '|'.

Community
  • 1
  • 1
diiN__________
  • 7,393
  • 6
  • 42
  • 69
0

If it was not for sql-server I would go with a regular expression to solve this problem.

This regular expression shows those substings to keep: ^[^|]+;|;[^|]+;|;[^|]+$
or this regular expression to cut those substrings to remove: ;[^;]+\|[^;]+

bw_üezi
  • 4,483
  • 4
  • 23
  • 41