How do I replace a substring of a string before a

2020-02-29 02:12发布

Table Email:

Values:

josh@yahoo.com
carmine32@hotmail.com
zehmaneh@yahoo.com

I want to replace the string before @ with test.

Result:

test@yahoo.com
test@hotmail.com
test@yahoo.com

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

4条回答
▲ chillily
2楼-- · 2020-02-29 02:32

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

查看更多
家丑人穷心不美
3楼-- · 2020-02-29 02:33

You could

select 'test' + substring(fld, charindex('@', fld), len(fld))
查看更多
成全新的幸福
4楼-- · 2020-02-29 02:35
declare @t table(email varchar(30))
insert @t values('josh@yahoo.com'),
                ('carmine32@hotmail.com'),
                ('zehmaneh@yahoo.com') 

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

Result:

Test@yahoo.com
Test@hotmail.com
Test@yahoo.com
查看更多
再贱就再见
5楼-- · 2020-02-29 02:47

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 = 'carmine32@hotmail.com'
PRINT 'test' + RIGHT(@email, charindex('@', REVERSE(@email)))
查看更多
登录 后发表回答