T-SQL 寻找字符第N次在字符串中出现的位置,拿走的给点个赞
转载请注明出处,联系我: t39q@163.com
本人热衷于数据库技术及算法的研究,志同道合之士, 欢迎探讨
create FUNCTION dbo.FindCharIndex
(@str NVARCHAR(4000), @find NVARCHAR(4000), @n SMALLINT)
RETURNS INT
AS
BEGIN
IF @n < 1
RETURN (0)
DECLARE @start SMALLINT
,@count SMALLINT
,@index SMALLINT
,@len SMALLINT
SET @index = CHARINDEX(@find, @str)
IF @index = 0
RETURN (0)
ELSE
SELECT
@count = 1
,@len = LEN(@find)
WHILE @index > 0
AND @count < @n
BEGIN
SET @start = @index + @len
SELECT
@index = CHARINDEX(@find, @str, @start)
,@count = @count + 1
END
IF @count < @n
SET @index = 0
RETURN (@index)
END;
GO