sql server中实现lastIndexOf



好久没有直接使用sql,前几天要在地址列中提取area信息,用lastIndexOF时出错,以为记错了函数名称,lastcharindex什么的都給搬上来了…。百度之后原来是sql里不支持lastindexof 不过可以用自定义函数或者存储过程来解决。

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[lastindexof] (@stringValue as nvarchar(1000), @stringSearch as nvarchar(1000), @startPosition as int = 0)
returns int
AS
BEGIN
     DECLARE @lastindex int
     SET @lastindex= 0
     DECLARE @tempindex int
     while (1=1)
     begin
        SET @tempindex = charindex(@stringSearch, @stringValue, @lastindex + 1)
        if (@tempindex = 0)
            break
        SET @lastindex = @tempindex
     end
    
     RETURN(@lastindex)
END

因为是一个比较小的应用,同样的也可以直接利用reserve反转字符串,再用charindex截取即可最后再反转也实现了需求。