SQLServer用函式實現對字串按照特定字元進行拆分

ywxj_001發表於2021-04-09

SQLServer用函式實現對字串按照特定字串進行拆分:

SQL 沒有split函式,因此需要實現一個函式來實現按照特定符號對字串進行拆分。


GO

/****** Object:  UserDefinedFunction [dbo].[SPLIT]    Script Date: 2020/4/22 9:59:14 ******/

SET ANSI_NULLS ON

GO

 

SET QUOTED_IDENTIFIER ON

GO

/*

名稱:SPLIT

功能描述:拆分字串

引數:

@SourceSql NVARCHAR(4000), 目標字串

@StrSeprate NVARCHAR(10), 間隔字串

返回值:

@temp TABLE(sl NVARCHAR(200)) 資料表

演算法:

示例:select * FROM dbo.SPLIT('A,B,C,D',',') 返回資料表

A

B

C

D

建立時間:2006-10-23

修改:

修改時間:

*/

 

CREATE  FUNCTION [dbo].[SPLIT](@SourceSql VARCHAR(max),@StrSeprate NVARCHAR(10))

RETURNS @temp TABLE(sl NVARCHAR(200))

AS 

BEGIN

DECLARE @i INT

SET @SourceSql=RTRIM(LTRIM(@SourceSql))

SET @i=CHARINDEX(@StrSeprate,@SourceSql)

WHILE @i>=1

BEGIN

INSERT @temp VALUES(LEFT(@SourceSql,@i-1))

SET @SourceSql=SUBSTRING(@SourceSql,@i+1,LEN(@SourceSql)-@i)

SET @i=CHARINDEX(@StrSeprate,@SourceSql)

END

INSERT @temp VALUES(@SourceSql)

RETURN 

END

 

GO


SELECT  * from  [dbo].[ SPLIT ] ( '1001,1002,1003' , ',' )


擴充套件一點:

傳入的是code的拼接,要求返回name的拼接;例如:輸入值為“1001,1002,1003”,返回為“哈哈哈,嘿嘿嘿,啦啦啦”;


/****** Object:  UserDefinedFunction [dbo].[FuncCompanySplite]    Script Date: 2020/4/22 10:04:15 ******/

SET ANSI_NULLS ON

GO

 

SET QUOTED_IDENTIFIER ON

GO

 

 

-- =============================================

-- Author: <Author,,>

-- Create date: <Create Date, ,>

-- Description: <Description, ,>

-- =============================================

CREATE FUNCTION [dbo].[FuncCompanySplite]

(

@SourceSql VARCHAR(max)

)

returns nvarchar(max)

AS

BEGIN

DECLARE @cropId nvarchar(50)

DECLARE @companyNm nvarchar(200)

DECLARE @companyNms nvarchar(max)

DECLARE @i INT

set @SourceSql = @SourceSql+','

SET @SourceSql=RTRIM(LTRIM(@SourceSql))

SET @i=CHARINDEX(',',@SourceSql)

WHILE @i>=1

BEGIN

set @cropId  =(LEFT(@SourceSql,@i-1))

select @companyNm=companyNm from DV_Company where companyId=@cropId;

if @companyNms is null

begin

set @companyNms = @companyNm

end

else begin  

set @companyNms = @companyNms +','+ @companyNm

end

SET @SourceSql=SUBSTRING(@SourceSql,@i+1,LEN(@SourceSql)-@i)

SET @i=CHARINDEX(',',@SourceSql)

END

 

    RETURN  @companyNms

 

END

GO



原文連結:https://blog.csdn.net/weixin_46867655/article/details/105675160






來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/22996654/viewspace-2767362/,如需轉載,請註明出處,否則將追究法律責任。

相關文章