简体   繁体   中英

SQL Server 2019 query returns all null values when trying to separate a single column into multiples columns of data

I have a table of data that uses a / as delimiter. I'm trying to separate the single column of data into three columns.

My query is returning the proper number of rows, but all three columns are NULL. Does anything jump off the page as obvious that I've missed?

Here is how the data is stored in the PGroup column:

Steve/Mouse/Vitamin
Matt/Cat/Soda
Shelly/Dog/Bread

I'm hoping to return 3 separate columns: Name, Pet, Food

DECLARE @delimiter VARCHAR(50)
SET @delimiter='/' 

;WITH CTE AS
(
    SELECT 
        CAST('' + REPLACE([PGroup], @delimiter, '') + '' AS XML) AS [PXML]
    FROM 
        xx123
)
SELECT
    [PXML].value('/M[1]', 'varchar(50)') As [Name],
    [PXML].value('/M[2]', 'varchar(50)') As [Pet],
    [PXML].value('/M[3]', 'varchar(50)') As [Food]
FROM 
    CTE

Please try the following solution.

Notable points:

  • CData section protects against XML entities like ampersand and the like.
  • XPath expressions were adjusted to use text() for performance reasons.

SQL

-- DDL and sample data population, start
DECLARE @tbl TABLE (ID INT IDENTITY PRIMARY KEY, tokens VARCHAR(1000));
INSERT INTO @tbl (tokens) VALUES
('Steve/Mouse/Vitamin'),
('Matt/Cat/Soda'),
('Shelly/Dog/Bread');
-- DDL and sample data population, end

DECLARE @separator CHAR(1) = '/';

SELECT ID
    , c.value('(/root/r[1]/text())[1]', 'varchar(50)') As [Name]
    , c.value('(/root/r[2]/text())[1]', 'varchar(50)') As [Pet]
    , c.value('(/root/r[3]/text())[1]', 'varchar(50)') As [Food]
FROM @tbl
CROSS APPLY (SELECT TRY_CAST('<root><r><![CDATA[' + 
        REPLACE(tokens, @separator, ']]></r><r><![CDATA[') + 
        ']]></r></root>' AS XML)) AS t(c);

Output

+----+--------+-------+---------+
| ID |  Name  |  Pet  |  Food   |
+----+--------+-------+---------+
|  1 | Steve  | Mouse | Vitamin |
|  2 | Matt   | Cat   | Soda    |
|  3 | Shelly | Dog   | Bread   |
+----+--------+-------+---------+

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM