CodexBloom - Programming Q&A Platform

Unexpected results when using CROSS APPLY with STRING_SPLIT in T-SQL

👀 Views: 0 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-13
sql-server t-sql string-split sql

I'm getting frustrated with I'm updating my dependencies and I'm testing a new approach and I'm working on a personal project and I'm working on SQL Server 2016, and I'm trying to parse a comma-separated string into rows using `STRING_SPLIT`, and then perform some calculations on each value... I need to join this with another table based on a condition but I'm getting unexpected results. Here's the scenario: I have a table `Orders` with a column `ItemIds` that contains a comma-separated list of item IDs. I want to join this with the `Items` table to get the item names. Here's my query: ```sql SELECT o.OrderId, i.ItemName FROM Orders o CROSS APPLY (SELECT value AS ItemId FROM STRING_SPLIT(o.ItemIds, ',')) AS split JOIN Items i ON split.ItemId = i.ItemId WHERE o.OrderDate >= '2023-01-01'; ``` However, when I run this query, I get a result set that contains duplicated `OrderId`s for each item in the `ItemIds`, which is expected, but the `ItemName` is not matching correctly. In some cases, it seems that I'm getting the same item name for different item IDs. I've already verified that the `ItemIds` column doesn't contain leading or trailing spaces. In addition, I tried using `TRIM` around `split.ItemId` in the join condition, but that didn't resolve the scenario. The `Items` table is indexed on `ItemId`, so I would expect decent performance as well. I'm also seeing the following behavior: If I add a `GROUP BY o.OrderId` clause to aggregate results, I get an behavior saying, "Column 'Items.ItemName' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause." This suggests that the join might be producing ambiguous results. Is there a better way to handle this situation without running into mismatched item names? Any help would be greatly appreciated! What's the best practice here? I recently upgraded to Sql 3.11. Thanks for your help in advance! The stack includes Sql and several other technologies. I'd really appreciate any guidance on this. I'm coming from a different tech stack and learning Sql. Any help would be greatly appreciated!