【问题标题】:How do I replace a substring of a string before a specific character?如何在特定字符之前替换字符串的子字符串?
【发布时间】:2012-09-04 12:01:23
【问题描述】:

表Email:

价值观:

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

我想用test替换@之前的字符串。

结果:

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

如何根据字符串中的字符使用子串和替换?

【问题讨论】:

  • 你使用任何服务器端语言吗?

标签: sql tsql replace substring


【解决方案1】:

你甚至不需要使用substring或replace,你可以使用这个:

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

你可以用这个来测试它:

DECLARE @email nvarchar(50)
SET @email = 'carmine32@hotmail.com'
PRINT 'test' + RIGHT(@email, charindex('@', REVERSE(@email)))

【讨论】:

  • @Testifier 你试过所有的解决方案了吗?
  • REVERSE 是 TSQL 中性能较低的字符串函数之一。
  • 我将它与 LEFT 一起使用以删除字符串末尾的任何尾随空格。它工作得很好。甚至像“this”这样的字符串也会返回“this”。感谢您的解决方案。
【解决方案2】:
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

结果:

Test@yahoo.com
Test@hotmail.com
Test@yahoo.com

【讨论】:

    【解决方案3】:

    您可以使用SUBSTRING 和CHARINDEX:

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

    小提琴:http://sqlfiddle.com/#!3/0face/6/0

    【讨论】:

      【解决方案4】:

      你可以

      select 'test' + substring(fld, charindex('@', fld), len(fld))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-10-20
        • 1970-01-01
        • 2019-08-19
        • 2020-10-04
        • 1970-01-01
        • 2014-10-29
        • 1970-01-01
        • 2015-06-16
        相关资源
        最近更新 更多