MSSQL:仿写MYSQL的substring_index 截断函数 F_SUBSTRING_INDEX
在博客里看《mysql根据分隔符将一行数据拆分成多行数据》文章,
MYSQL中有系统函数 SUBSTRING_INDEX(), 方便地实现了“一行数据拆分成多行”,
SQL SERVER使用都可没这么好了。因此,我在SQL SERVER 2008中仿写了一个自定义函数 f_substring_index() 。
详细代码如下:
/*
Returns the substring from string str before count occurrences of the
delimiter delim. If count is positive, everything to the left of the
final delimiter (counting from the left) is returned. If count is
negative, everything to the right of the final delimiter (counting from
the right) is returned. SUBSTRING_INDEX() performs a case-sensitive
match when searching for delim.
*/
alter FUNCTION DBO.F_SUBSTRING_INDEX(
@str NVARCHAR(4000),
@delim NVARCHAR(128),
@count INT
)RETURNS NVARCHAR(256)
AS
BEGIN
-- F_SUBSTRING_INDEX():截斷函數,同MYSQL的SUBSTRING_INDEX();
-- @str: 要處理的字符串
-- @delim: 分隔符
-- @count: 計數,如果@COUNT是正數,那麼就是從左往右數,第N個分隔符的左邊的全部內容
-- 相反,如果是負數,那麼就是從右邊開始數,第N個分隔符右邊的所有內容。
--
DECLARE @RESULT NVARCHAR(256);
declare @index int;
declare @i int =0 ;
DECLARE @pos int=0 -- 記錄位置
DECLARE @times INT =0 -- 記錄找的次數
declare @stringLength int = 0;
declare @ReverseStr varchar(4000);
set @stringLength = LEN(@str);
if @count>0
begin
-- 1、先考慮存在分隔符
-- while @i < @stringLength
begin
WHILE(@times<@count)
BEGIN
begin
SET @times = @times+1
set @pos = CHARINDEX(@delim,@str,@pos+1)
end;
END
end
-- 2、考慮不存在分隔符,計數超出分隔符總數量
if @pos = 0
set @index = @stringLength
else
set @index = @pos
-- cal:
if @pos>=1
set @RESULT = SUBSTRING(@str,1,@index -1);
else
set @RESULT= SUBSTRING(@str,1,@stringLength);
end;
else IF @count < 0
begin
SET @pos =0;
set @ReverseStr = REVERSE(@str);
-- 1、先考慮存在分隔符
-- while @i < @stringLength
begin
WHILE(@times<abs(@count))
BEGIN
begin
SET @times = @times+1
set @pos = CHARINDEX(REVERSE(@delim),@ReverseStr,@pos+1)
end;
END
end
-- 2、考慮不存在分隔符,計數超出分隔符總數量
if @pos = 0
set @index = @stringLength
else
set @index = @pos
-- cal:
if @pos>=1
set @RESULT = reverse(SUBSTRING(@ReverseStr,1,@index -1));
else
set @RESULT= reverse(SUBSTRING(@ReverseStr,1,@stringLength));
end;
else
set @RESULT = N'';
RETURN @RESULT;
END;
go
调试实例:
SELECT DBO.F_SUBSTRING_INDEX( 'Aa,Bb,Cc,df,hgk',',',2) AS SUBSTRING_INDEX2
,DBO.F_SUBSTRING_INDEX( 'Aa,Bb,Cc,df,hgk',',',0) AS REVERSE_INDEX0
,DBO.F_SUBSTRING_INDEX( 'Aa,Bb,Cc,df,hgk',',',-1) AS REVERSE_INDEX
,DBO.F_SUBSTRING_INDEX( 'Aa,Bb,Cc,df,hgk',',',1) AS REVERSE_INDEX1
-- 返回:
/*
SUBSTRING_INDEX2 REVERSE_INDEX0 REVERSE_INDEX REVERSE_INDEX1
---------------- -------------- ------------- --------------
Aa,Bb NULL hgk Aa
*/
go
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了