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