Regex in SQL Server using replace

836 views Asked by At

I want to change '@sadim Hi, blah blah blah.' to 'Hi, blah blah blah.' in SQL Server.

I use this query but it doesn't work :

update mytable
set ttext = REPLACE(ttext, '@% ' , '');
2

There are 2 answers

0
Ampati Hareesh On BEST ANSWER
update stack
set name = SUBSTRING(name,CHARINDEX(' ',name),LEN(name));

This will allow you to skip the @Username part. as the string is starting with the @username get the sub String after that Here stack is your table and name is your column name

Coming to regex part Please have a look into this

https://dba.stackexchange.com/questions/162816/sql-server-replace-with-wildcards

If at all @username exists in middle of the string use this:

update stack
set name =
case 
    when name like '@%' then SUBSTRING(name,CHARINDEX(' ',name),LEN(name))
    when name like '%@%' then CONCAT(
        SUBSTRING(name,0,CHARINDEX('@',name)-1),
        SUBSTRING(SUBSTRING(name,CHARINDEX('@',name),LEN(name)),
                  CHARINDEX(' ',
                           SUBSTRING(name,CHARINDEX('@',name),LEN(name))),
                  LEN(
                      SUBSTRING(name,CHARINDEX('@',name),LEN(name))
                      )
                  )

        )

end
0
Nandish B On

use the below update query

update mytable
set ttext = (select substring(ttext,charindex(' ',ttext)+1,len(ttext) - charindex(' ',ttext)));