类似以下的内容可用于获取您请求的输出(不记得我从哪里抢走了 ParseString 函数 - 但我一直在使用它,效果很好)
CREATE FUNCTION dbo.fnParseString
(
@Section SMALLINT ,
@Delimiter CHAR ,
@Text VARCHAR(MAX)
)
RETURNS VARCHAR(8000)
AS
BEGIN
DECLARE @NextPos SMALLINT ,
@LastPos SMALLINT ,
@Found SMALLINT
--#### Uncomment the following 2 lines to emulate PARSENAME functionality
--IF @Section > 0
-- SELECT @Text = REVERSE(@Text)
SELECT @NextPos = CHARINDEX(@Delimiter, @Text, 1) ,
@LastPos = 0 ,
@Found = 1
WHILE @NextPos > 0
AND ABS(@Section) <> @Found
SELECT @LastPos = @NextPos ,
@NextPos = CHARINDEX(@Delimiter, @Text, @NextPos + 1) ,
@Found = @Found + 1
RETURN CASE
WHEN @Found <> ABS(@Section) OR @Section = 0 THEN NULL
--#### Uncomment the following lines to emulate PARSENAME functionality
--WHEN @Section > 0 THEN REVERSE(SUBSTRING(@Text, @LastPos + 1, CASE WHEN @NextPos = 0 THEN DATALENGTH(@Text) - @LastPos ELSE @NextPos - @LastPos - 1 END))
WHEN @Section > 0 THEN SUBSTRING(@Text, @LastPos + 1, CASE WHEN @NextPos = 0 THEN DATALENGTH(@Text) - @LastPos ELSE @NextPos - @LastPos - 1 END)
ELSE SUBSTRING(@Text, @LastPos + 1, CASE WHEN @NextPos = 0 THEN DATALENGTH(@Text) - @LastPos ELSE @NextPos - @LastPos - 1 END)
END
END
DECLARE @TestData VARCHAR(255)
SET @TestData = 'business.unit.explored.wrong.way'
SELECT dbo.fnParseString(2, '.', @TestData) ,
dbo.fnParseString(3, '.', @TestData) ,
dbo.fnParseString(4, '.', @TestData) ,
dbo.fnParseString(5, '.', @TestData) ,
dbo.fnParseString(6, '.', @TestData)