FOR XML PATH, STRING_AGG and AI

For the AI warriors out there – I was rewriting a bunch of stored procedures (270+, to be more precise), so naturally AI comes into play (QWEN Coder Next 80B at 8 bit and GPT-OSS 120B MXFP4 – not as precise, but works good enough. Yes, I need to work with local models because of the very sensitive data I get to see). I usually end up with stored_proc_name and stored_proc_name_V1, where the _V1 is chosen from a bunch of different paths I explore. In many cases I see the AI telling me to replace FOR XML PATH with STRING_AGG function.

Now, consider the following scenario.

The XML PATH (“old”) stored procedure:

USE AdventureWorks;
GO

CREATE OR ALTER PROCEDURE dbo.usp_Performance_ForXmlPath
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @StartTime DATETIME2(7) = SYSDATETIME();

    SELECT soh.SalesOrderID,
           STUFF(
                    (
                        SELECT N', ' + p2.Name
                        FROM Sales.SalesOrderDetail AS sod2
                            INNER JOIN Production.Product AS p2
                                ON p2.ProductID = sod2.ProductID
                        WHERE sod2.SalesOrderID = soh.SalesOrderID
                        ORDER BY p2.Name
                        FOR XML PATH(''), TYPE
                    ).value('.', 'nvarchar(max)'),
                    1,
                    2,
                    N''
                ) AS ProductList
    FROM Sales.SalesOrderHeader AS soh
    ORDER BY soh.SalesOrderID DESC;
END;
GO

The STRING_AGG (“new”) procedure (basically a rewrite of the “old” XML PATH procedure, as rewritten by AI:

USE AdventureWorks;
GO

CREATE OR ALTER PROCEDURE dbo.usp_Performance_StringAgg
AS
BEGIN
SET NOCOUNT ON;

DECLARE @StartTime DATETIME2(7) = SYSDATETIME();

SELECT sod.SalesOrderID,
STRING_AGG(CONVERT(NVARCHAR(MAX), p.Name), N', ') WITHIN GROUP(ORDER BY p.Name) AS ProductList
FROM Sales.SalesOrderDetail AS sod
INNER JOIN Production.Product AS p
ON p.ProductID = sod.ProductID
GROUP BY sod.SalesOrderID
ORDER BY sod.SalesOrderID DESC;
END;
GO

A side note for the ones too lazy to run the scripts: they simply return the products as a product list for each invoice. Yes, they return the same result. Moving on.

Now, for the big question, assuming your prod server is a highly concurrent Azure MI Business Critical tier, which of the above stored procedures should make it to prod? And, more importantly, WHY?

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.