Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I replace a substring of a string before a specific character?

Table Email:

Values:

[email protected]
[email protected]
[email protected]

I want to replace the string before @ with test.

Result:

[email protected]
[email protected]
[email protected]

How do I use substringing and replace based on a character in the string?

like image 514
JJ. Avatar asked Sep 11 '12 14:09

JJ.


3 Answers

declare @t table(email varchar(30))
insert @t values('[email protected]'),
                ('[email protected]'),
                ('[email protected]') 

select stuff(email, 1, charindex('@', email), 'Test@') 
from @t

Result:

[email protected]
[email protected]
[email protected]
like image 44
t-clausen.dk Avatar answered Oct 03 '22 16:10

t-clausen.dk


You don't even need to use substring or replace, you can use this:

SELECT 'test' + RIGHT(email, charindex('@', REVERSE(email)))
FROM YourTable

You can test it out with this:

DECLARE @email nvarchar(50)
SET @email = '[email protected]'
PRINT 'test' + RIGHT(@email, charindex('@', REVERSE(@email)))
like image 111
LittleBobbyTables - Au Revoir Avatar answered Oct 03 '22 14:10

LittleBobbyTables - Au Revoir


You can use SUBSTRING and CHARINDEX:

UPDATE Email set email = 
    'test' + SUBSTRING(email, CHARINDEX('@',email), LEN(email))

Fiddle: http://sqlfiddle.com/#!3/0face/6/0

like image 2
Tim Schmelter Avatar answered Oct 03 '22 16:10

Tim Schmelter