拆分字符串并删除最后一个值

Split string and Remove last value

我必须使用 '/' 拆分字符串。

输入:

INTC/MODB2/0241-07133/0010-81717/0010-36299

我必须遍历它,预期输出如下:

INTC/MODB2/0241-07133/0010-81717/0010-36299
INTC/MODB2/0241-07133/0010-81717
INTC/MODB2/0241-07133
INTC/MODB2
INTC

我尝试使用拆分功能,但我能够打印出准确的输出

SELECT value 
FROM STRING_SPLIT('INTC/MODB2/0241-07133/0010-81717/0010-36299', '/');

感谢任何帮助

答案:

递归 CTE 是一个选项:

DECLARE @text varchar(1000) = 'INTC/MODB2/0241-07133/0010-81717/0010-36299'
DECLARE @separator varchar(1) = '/';

WITH rCTE AS(
    SELECT CHARINDEX(@separator, CONCAT(@text, @separator)) As Position
    UNION ALL
    SELECT CHARINDEX(@separator, CONCAT(@text, @separator), Position + 1) AS Position
    FROM rCTE
    WHERE CHARINDEX(@separator, CONCAT(@text, @separator), Position + 1) > 0
)
SELECT SUBSTRING(CONCAT(@text, @separator), 1, Position - 1) AS [Value]
FROM rCTE
ORDER BY Position DESC
OPTION (MAXRECURSION 0)

结果:

Value
-------------------------------------------
INTC/MODB2/0241-07133/0010-81717/0010-36299
INTC/MODB2/0241-07133/0010-81717
INTC/MODB2/0241-07133
INTC/MODB2
INTC

更新:

如果文本存储在table中,则需要不同的语句:

Table:

CREATE TABLE Data (Id int, Notes varchar(1000))
INSERT INTO Data 
VALUES 
   (1, 'INTC/MODB2/0241-07133/0010-81717/0010-36299'),
   (2, 'ABCD/0010-36299')

声明:

DECLARE @separator varchar(1) = '/';
WITH rCTE AS(
    SELECT
       d.Id,
       d.Notes,
       CHARINDEX(@separator, CONCAT(d.Notes, @separator)) AS Position
    FROM Data d   
    UNION ALL
    SELECT
       r.Id,
       r.Notes,
       CHARINDEX(@separator, CONCAT(r.Notes, @separator), r.Position + 1) AS Position
    FROM rCTE r
    WHERE CHARINDEX(@separator, CONCAT(r.Notes, @separator), r.Position + 1) > 0
)
SELECT Id, SUBSTRING(CONCAT(Notes, @separator), 1, Position - 1) AS [Value]
FROM rCTE
ORDER BY Id, Position DESC
OPTION (MAXRECURSION 0)