首先,创建一个简单的字符串拆分函数:
CREATE FUNCTION [dbo].[SplitString]
(
@List NVARCHAR(MAX),
@Delim VARCHAR(255)
)
RETURNS TABLE
AS
RETURN ( SELECT [Value] FROM
(
SELECT
[Value] = LTRIM(RTRIM(SUBSTRING(@List, [Number],
CHARINDEX(@Delim, @List + @Delim, [Number]) - [Number])))
FROM (SELECT Number = ROW_NUMBER() OVER (ORDER BY name)
FROM sys.all_objects) AS x
WHERE Number <= LEN(@List)
AND SUBSTRING(@Delim + @List, [Number], LEN(@Delim)) = @Delim
) AS y
);
然后,您可以在以下位置使用它OUTER APPLY
:
declare @T table (id int, fname varchar(50), tname varchar(50), email varchar(200))
insert into @T values (1, 'fname1', 'tname1', 'xxxxxx@msn.com xxx.xxxxx.com')
insert into @T values (2, 'fname2', 'tname2', 'just a bunch of usless data')
insert into @T values (3, 'fname3', 'tname3', 'xxx@xx.xx.com')
insert into @T values (4, 'fname4', 'tname4', 'xxx@xx.xx.com xxx@yahoo.com')
insert into @T values (5, 'fname5', 'tname5', 'xxx@gmail.com xxxx.msn.com')
insert into @T values (3, 'fname6', 'tname6', 'xxx@msn.com')
SELECT t.id, t.fname, t.tname, f.Value
FROM @T AS t
OUTER APPLY dbo.SplitString(REPLACE(t.email, ' ', ';'), ';') AS f
WHERE t.email LIKE '%@%' AND f.Value LIKE '%@%';
结果:
id fname tname Value
---- ------ ------ --------------
1 fname1 tname1 xxxxxx@msn.com
3 fname3 tname3 xxx@xx.xx.com
4 fname4 tname4 xxx@xx.xx.com
4 fname4 tname4 xxx@yahoo.com
5 fname5 tname5 xxx@gmail.com
3 fname6 tname6 xxx@msn.com
有关拆分函数的更多信息(以及更好的替代方案,如果拆分来自应用程序层的字符串):
http://www.sqlperformance.com/2012/07/t-sql-queries/split-strings
http://www.sqlperformance.com/2012/08/t-sql-queries/splitting-strings-now-with-less-t-sql