BIG阳
首先,创建一个函数(使用CTE,公共表表达式不需要临时表) create function dbo.SplitString ( @str nvarchar(4000), @separator char(1) ) returns table AS return ( with tokens(p, a, b) AS ( select 1, 1, charindex(@separator, @str) union all select p + 1, b + 1, charindex(@separator, @str, b + 1) from tokens where b > 0 ) select p-1 zeroBasedOccurance, substring( @str, a, case when b > 0 then b-a ELSE 4000 end) AS s from tokens ) GO然后,将它用作任何表(或修改它以适合您现有的存储过程),就像这样。select s from dbo.SplitString('Hello John Smith', ' ')where zeroBasedOccurance=1更新对于长度超过4000个字符的输入字符串,以前的版本将失败。此版本负责限制:create function dbo.SplitString ( @str nvarchar(max), @separator char(1))returns tableASreturn (with tokens(p, a, b) AS ( select cast(1 as bigint), cast(1 as bigint), charindex(@separator, @str) union all select p + 1, b + 1, charindex(@separator, @str, b + 1) from tokens where b > 0)select p-1 ItemIndex, substring( @str, a, case when b > 0 then b-a ELSE LEN(@str) end) AS sfrom tokens);GO用法保持不变。