函數返回一個用分隔符連接起的字符串,其中每個單位的字符串不重復存在

/****************************************************************************************************************************
Name:   ufn_SerialString  

Description: 函數返回一個用分隔符連接起的字符串,其中每個單位的字符串不重復存在

Parameters:   IN - @strBase - 連接在一起的字符串
     IN - @strNew - 新加入的字符串
     IN - @strSplitChar - 分隔符

Return:   連接在一起的字符串

Usage:   create table #temp(strValue varchar(10))
    insert #temp select 'a'
    union all select 'b'
    union all select 'c'
    union all select 'b'
    union all select 'a'
    select strValue as N'原始數據' from #temp
    declare @str varchar(1000)
    select @str=dbo.ufn_SerialString(@str,strValue,',') from #temp
    print '===================================================================================='
    select @str as N'連接之後的字符串'
    drop table #temp

Calling functions:    System     Module

****************************************************************************************************************************/
CREATE FUNCTION [dbo].[ufn_SerialString] (@strBase NVARCHAR(4000),
      @strNew NVARCHAR(4000),
      @strSplitChar NVARCHAR(1)='/')
RETURNS NVARCHAR(4000) AS
BEGIN
SET @strBase=RTRIM(ISNULL(@strBase,''))
SET @strNew=RTRIM(ISNULL(@strNew,''))
SET @strBase=CASE WHEN @strBase='' THEN @strNew
   WHEN @strNew='' OR CHARINDEX(@strSplitChar+@strNew+@strSplitChar,@strSplitChar+@strBase+@strSplitChar)>0 THEN @strBase
   ELSE @strBase+@strSplitChar+@strNew END
RETURN @strBase
END

原文地址:https://www.cnblogs.com/guyuehuanhuan/p/1942274.html