Search code examples
t-sqlazure-synapse

Remove first comma in string TSQL


I am trying to prune tags if 'وسم' is mentioned, but when doing so, the first comma still remains.

--drop tags like 'وسم' 
drop table temp
CREATE TABLE temp (tags NVARCHAR(1500));
INSERT INTO temp values(N'تفاحة, أناناس, وسم')
INSERT INTO temp values(N'تفاحة, موز, برتقال, وسم, العنب')

I tried running this:

    set temp.tags = replace(tags,N'وسم,','')
    where tags like N'%وسم%'
    update temp
    set temp.tags = replace(tags,N'وسم','')
    where tags like N'%وسم%'

and this was the output:

تفاحة, أناناس,
تفاحة, موز, برتقال, العنب

what it should be ideally:

تفاحة, أناناس
تفاحة, موز, برتقال, العنب

What i have also tried running was:

UPDATE temp
SET temp.tags =  case when charindex(',',temp.tags,0) =1 then right(temp.tags, len(temp.tags)-1) else temp.tags end

I ended up getting the same output where there is comma in the beginning of the string.


Solution

  • I see you have a space between وسم and ,

    You may want to consider replacing all of the following

    update temp 
    set temp.tags = replace(tags,N'وسم,','');
    
    update temp 
    set temp.tags = replace(tags,N',وسم','');
    
    update temp 
    set temp.tags = replace(tags,N', وسم','');
    
    update temp 
    set temp.tags = replace(tags,N'وسم ,','');