标量值函数

/*
切割字符串并根据元素索引值获取元素
例如:a,b,c , 2 返回b 不存在返回空 
    验证如下:if ISNULL(@element,'')=''
        print('不存在')
*/
ALTER FUNCTION [dbo].[GetElementByIndex]
(
    @text varchar(5000), --14123|10|商品名称|
    @split_str varchar(100), --|
    @index int -- 2
)
RETURNS varchar(1000)
AS
BEGIN
    set @text=@text+@split_str
    declare @i int=0 --元素位置
    declare @element varchar(1000)--记录元素的值
    declare @s_index int=1
    declare @e_index int=0
    set @e_index=CHARINDEX(@split_str,@text)
    while @e_index>0
    begin
        set @element=SUBSTRING(@text,@s_index,@e_index-@s_index)
        set @i=@i+1
        if @i=@index return @element
        set @text=SUBSTRING(@text,@e_index+LEN(@split_str),len(@text)-@e_index)        
        set @e_index=CHARINDEX(@split_str,@text)
    end 
    return ''
END
View Code