SQL Server字符串切割函数

前端之家收集整理的这篇文章主要介绍了SQL Server字符串切割函数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

<div class="codetitle"><a style="CURSOR: pointer" data="14875" class="copybut" id="copybut14875" onclick="doCopy('code14875')"> 代码如下:

<div class="codebody" id="code14875">
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,@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('64500201_45854_18367712','')
PRINT @value

结果:
645002
01
--1 45854 --2 183677

原文链接:https://www.f2er.com/mssql/63768.html

猜你在找的MsSQL相关文章