SQL Server字符串切割函數。本站提示廣大學習愛好者:(SQL Server字符串切割函數)文章只能為提供參考,不一定能成為您想要的結果。以下是SQL Server字符串切割函數正文
CREATE FUNCTION fGetStrBySplit
(
@Source VARCHAR(max),
@Index INT,
@SplitChar VARCHAR(1)
)
RETURNS varchar(MAX)
AS
BEGIN
DECLARE @Len INT
DECLARE @n INT = 0
DECLARE @ChIndex INT
DECLARE @Result VARCHAR(MAX)
--獲得總長度
SET @Len = LEN(@Source)
--獲得切割字符地位
SET @ChIndex = CHARINDEX(@SplitChar,@Source)
WHILE @ChIndex > 0
BEGIN
IF(@n = @Index)
BEGIN
SET @Source = SUBSTRING(@Source,0,@ChIndex)
BREAK
END
SET @Source = SUBSTRING(@Source,@ChIndex+1,@Len)
SET @ChIndex = CHARINDEX(@SplitChar,@Source)
SET @Len = LEN(@Source)
SET @n = @n + 1
END
RETURN @Source
END
GO
--挪用
DECLARE @value VARCHAR(max)
SET @value = dbo.fGetStrBySplit('645002*01_45854_183677_12',0,'_')
PRINT @value
成果:
645002*01
--1
45854
--2
183677