我想在SQL服务器中分割字符串并获取@之前和任何其他特殊字符之后的值。
Example 1: I have a string
<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ef8e8d8cc1dedddcc1998a9baf979695c18c8082" rel="noreferrer noopener nofollow">[email protected]</a>
Expected output: vet
Example 2: <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="47262626073e3e6924282a" rel="noreferrer noopener nofollow">[email protected]</a>
Expected output: aaa
Example 3: aaa <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fc9e8899bc8585d29f9391" rel="noreferrer noopener nofollow">[email protected]</a>
Expected output: bte
我已经尝试过:
代码片段#1:
DECLARE @email VARCHAR(100)
SET @email = '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="57313e25242339363a32793b36242339363a3217323a363e3b7934383a" rel="noreferrer noopener nofollow">[email protected]</a>'
SELECT SUBSTRING(@email, 0, CHARINDEX('@', @email))
代码片段#2:
DECLARE @emai1l VARCHAR(100)
SET @emai1l = '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="87e1eef5f4f3a9e9e6eae2a9ebe6f4f3e9e6eae2c7e2eae6eeeba9e4e8ea" rel="noreferrer noopener nofollow">[email protected]</a>'
SELECT SUBSTRING(SUBSTRING(@emai1l, 0, CHARINDEX('@', @emai1l)), 0, CHARINDEX('.', @emai1l))
最佳答案
对于这种类型的字符串操作,SQL Server 并不是最佳选择。不过,这里有一种方法:
select t.str, v.str,
right(v.str,
patindex('%[, .]%', reverse(v.str) + ' ') - 1
) as result
from (values ('<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="513033327f6063627f2734251129282b7f323e3c" rel="noreferrer noopener nofollow">[email protected]</a>'), ('<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b7d6d6d6f7cece99d4d8da" rel="noreferrer noopener nofollow">[email protected]</a>'), ('aaa <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="412335240138386f222e2c" rel="noreferrer noopener nofollow">[email protected]</a>')
) t(str) cross apply
(values (left(t.str, charindex('@', t.str) - 1))
) v(str) ;
Here是一个数据库<> fiddle 。
关于sql - 我想获取 SQL Server 中 @ 之前和任何其他特殊字符或空格之后的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63687835/