sqlserver中计算某个特殊字符在字符串中出现的位置

-- =============================================  
-- Author:  Evan  
-- Create date: 2018年3月15日10:59:45
-- Description: 计算某特殊字符在字符串中出现的位置
-- ============================================= 
/*
返回@find在@str中第(@n)次出现的位置。没有第(@n)次返回0。
*/
Create function [dbo].[Fn_FindIndex](@find varchar(8000), @str varchar(8000), @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

EX:SELECT dbo.Fn_FindIndex('|','63514-18010000001|10|0',2)

posted @ 2018-03-15 11:04  Evan_Zhang  阅读(1026)  评论(0)    收藏  举报