gpt4 book ai didi

sql - 如何从 SQL Server 中的单行中提取多个字符串

转载 作者:行者123 更新时间:2023-12-05 00:34:17 24 4
gpt4 key购买 nike

我有例如下表数据:

id    |    text
--------------------------------------------------------------------------------
1 | Peter (Peter@peter.de) and Marta (marty@gmail.com) are doing fine.
2 | Nothing special here
3 | Another email address (me@my.com)

现在我需要一个 select 来从我的文本列中返回所有电子邮件地址(可以只检查括号),如果文本中有多个地址,它会返回多行柱子。我知道how to extract the first element ,但我完全不知道如何找到第二个和更多的结果。

最佳答案

您可以递归地使用 cte 来剥离字符串。

declare @T table (id int, [text] nvarchar(max))

insert into @T values (1, 'Peter (Peter@peter.de) and Marta (marty@gmail.com) are doing fine.')
insert into @T values (2, 'Nothing special here')
insert into @T values (3, 'Another email address (me@my.com)')

;with cte([text], email)
as
(
select
right([text], len([text]) - charindex(')', [text], 0)),
substring([text], charindex('(', [text], 0) + 1, charindex(')', [text], 0) - charindex('(', [text], 0) - 1)
from @T
where charindex('(', [text], 0) > 0
union all
select
right([text], len([text]) - charindex(')', [text], 0)),
substring([text], charindex('(', [text], 0) + 1, charindex(')', [text], 0) - charindex('(', [text], 0) - 1)
from cte
where charindex('(', [text], 0) > 0
)
select email
from cte

结果

email
Peter@peter.de
me@my.com
marty@gmail.com

关于sql - 如何从 SQL Server 中的单行中提取多个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4843121/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com