我在表的一列中有以下数据,我想将其拆分成更多的列。在此场景中,使用|
作为分隔符。列标题应在其值之前:& after Column是它的值。
Column
-----------------------------------------------------------------------------
ID: 30000300 | Name: India | Use: New Use
ID: 30000400 | Name: Aus | New ID: 15625616 | Address 1: NEW Rd
ID: 30000400 | Name: USA | City: VIA ARAMAC | New ID: 123
ID: 30000500 | Name: Russia | New ID: 15624951 | Address 2: 2131 BEAUDESERT
输出应为:
ID Name Use New ID City Address 1 Address 2 New City
----------------------------------------------------------------------
30000300 India New Use
30000400 Aus 15625616 NEW Rd
30000400 USA 15625616 VIA ARAMAC GALILEE
30000500 Russia 15624951 2131 BEAUDESERT
发布于 2019-07-10 03:17:30
以下是部分答案,您可以使用它返回分隔字符串中的第n个条目:
DECLARE @DelimitedString VARCHAR(8000);
DECLARE @Delimiter VARCHAR(100);
DECLARE @indexToReturn INT;
DECLARE @tblArray TABLE
(
ElementID INT IDENTITY(1, 1), -- Array index
Element VARCHAR(1000) -- Array element contents
);
-- Local Variable Declarations
-- ---------------------------
DECLARE @Index SMALLINT,
@Start SMALLINT,
@DelSize SMALLINT;
SET @DelSize = LEN(@Delimiter + 'x') - 1;
-- Loop through source string and add elements to destination table array
-- ----------------------------------------------------------------------
WHILE LEN(@DelimitedString) > 0
BEGIN
SET @Index = CHARINDEX(@Delimiter, @DelimitedString);
IF @Index = 0
BEGIN
INSERT INTO @tblArray
(
Element
)
VALUES
(LTRIM(RTRIM(@DelimitedString)));
BREAK;
END;
ELSE
BEGIN
INSERT INTO @tblArray
(
Element
)
VALUES
(LTRIM(RTRIM(SUBSTRING(@DelimitedString, 1, @Index - 1))));
SET @Start = @Index + @DelSize;
SET @DelimitedString = SUBSTRING(@DelimitedString, @Start, LEN(@DelimitedString) - @Start + 1);
END;
END;
DECLARE @val VARCHAR(1000);
SELECT @val = Element
FROM @tblArray AS ta
WHERE ta.ElementID = @indexToReturn;
SELECT @val;
https://stackoverflow.com/questions/56958871
复制相似问题