我真的不知道该怎么做,我对 SQL 有点陌生。我应该使用substring还是replace在我的情况下?
我的数据库中有一个名为“email”的字段,现在我想将所有以“email.com”结尾的电子邮件编辑为“email.org”。我该怎么办?
我真的不知道该怎么做,我对 SQL 有点陌生。我应该使用substring还是replace在我的情况下?
我的数据库中有一个名为“email”的字段,现在我想将所有以“email.com”结尾的电子邮件编辑为“email.org”。我该怎么办?
这取决于你需要做什么。您可以使用replace,因为您想替换该值:
select replace(email, '.com', '.org')
from yourtable
然后到UPDATE你的桌子上用新的结尾,然后你会使用:
update yourtable
set email = replace(email, '.com', '.org')
您还可以通过检查电子邮件值的最后 4 个字符来对此进行扩展:
update yourtable
set email = replace(email, '.com', '.org')
where right(email, 4) = '.com'
但是,问题replace()在于.com电子邮件中的其他位置可能会出现,而不仅仅是最后一个。因此,您可能希望使用substring()以下方式:
update yourtable
set email = substring(email, 1, len(email) -4)+'.org'
where right(email, 4) = '.com';
使用substring()将返回电子邮件值的开头,没有结尾.com,然后将 连接.org到结尾。这可以防止替换.com字符串中的其他位置。
或者,您可以使用stuff(),它允许您同时进行删除和插入:
update yourtable
set email = stuff(email, len(email) - 3, 4, '.org')
where right(email, 4) = '.com';
这将删除最后一个字符之前第三个字符位置的 4 个字符(即 final 的起始位置.com)并插入.org。
有关此方法,请参阅SQL Fiddle with Demo 。
You could just use REPLACE:
UPDATE myTable SET emailCol = REPLACE(emailCol, '.com', '.org')`.
But take into account an email address such as john.comrad@some.company.com will be updated to john.orgrad@some.organy.org.
If you want to be on a safer side, you should check for the last 4 characters using RIGHT, and append .org to the SUBSTRING manually instead. Notice the usage of UPPER to make the search for the .com ending case insensitive.
UPDATE myTable
SET emailCol = SUBSTRING(emailCol, 1, LEN(emailCol)-4) + '.org'
WHERE UPPER(RIGHT(emailCol,4)) = '.COM';
See it working in this SQLFiddle.
为避免包含.comlike john.comrad@email.comto 的更新名称john.orgrad@email.org,您可以这样做:
UPDATE Yourtable
SET Email = LEFT(@Email, LEN(@Email) - 4) + REPLACE(RIGHT(@Email, 4), '.com', '.org')
试试这个查询,它会改变以 .com 结尾的记录
UPDATE tablename SET email = replace(email, '.com', '.org') WHERE email LIKE '%.com';