Hi @tom pratt,
Please try the following solution.
I used a CTE for the answer. But in the real world, you can create a view for that.
-- DDL and sample data population, start
DECLARE @tbl TABLE (
ProductID nvarchar(25) NULL,
[Name] nvarchar(25) NULL,
ParentID nvarchar(51) NULL,
AttributeType nvarchar(10) NULL,
AttributeID nvarchar(255) NULL,
UnitID nvarchar(255) NULL,
AttributeValue nvarchar(4000) NULL
);
INSERT INTO @tbl (ProductID, [Name], ParentID, AttributeType, AttributeID, UnitID, AttributeValue)
VALUES
('1160577','TCF40','39121606_4903','Value','Connection',NULL,'Blade end'),
('1160577','TCF40','39121606_4903','Value','Mounting',NULL,'35 mm DIN Rail, Chassis'),
('1160577','TCF40','39121606_4903','MultiValue','Size','unit.Dime.Inches','MOL: 5, MOD: 2.63'),
('1160577','TCF40','39121606_4903','MultiValue','Color',NULL,'Frost'),
('886092','RC2163BFE','39121552_4775','Value','Connection',NULL,'Blade end'),
('886092','RC2163BFE','39121552_4775','Value','Mounting',NULL,'35 mm DIN Rail, Chassis'),
('886092','RC2163BFE','39121552_4775','Value','Lumens','unit.Elec.Lumens','2.9k');
-- DDL and sample data population, end
SELECT * FROM @tbl
--FOR XML PATH('r'), TYPE, ROOT('root');
;WITH rs AS
(
SELECT ProductID, Name, ParentID, AttributeType, AttributeID, UnitID, AttributeValue = TRIM([value])
FROM @tbl AS c
CROSS APPLY STRING_SPLIT(AttributeValue, ',')
WHERE AttributeType='MultiValue'
UNION ALL
SELECT ProductID, Name, ParentID, AttributeType, AttributeID, UnitID, AttributeValue
FROM @tbl AS c
WHERE AttributeType='Value'
)
SELECT 'Context1' AS [@ImportContext]
, 'Context1' AS [@ContextID]
, 'Main' AS [@WorkspaceID]
, 'false' AS [@UseContextLocale]
, (
SELECT ProductID AS [@ID]
, 'CatalogNumber' AS [@UserTypeID]
, ParentID AS [@ParentID]
, Name AS [Name]
, (
SELECT AttributeType, AttributeID, UnitID, AttributeValue
FROM rs AS c
WHERE p.ProductID = c.ProductID
AND p.ParentID = c.ParentID
AND p.[Name] = c.[Name]
FOR XML PATH('r'), TYPE, ROOT('root')
)
.query('<Values>
{
for $x in /root/r[AttributeType="Value"]
return <Value AttributeID="{data($x/AttributeID)}">
{if ($x/UnitID) then attribute UnitID {data($x/UnitID)} else ()}
{data($x/AttributeValue)}
</Value>,
if (/root/r[AttributeType="MultiValue"]) then
for $x in distinct-values(/root/r[AttributeType="MultiValue"]/AttributeID)
return <MultiValue AttributeID="{$x}">
{
for $y in /root/r[AttributeID/text()=$x]
return <Value>
{
if ($y[AttributeID/text()=$x]/UnitID) then
attribute UnitID {$y[AttributeID/text()=$x]/UnitID/text()}
else ()
}
{data($y/AttributeValue)}
</Value>
}
</MultiValue>
else ()
}
</Values>')
FROM rs AS p
GROUP BY ProductID, ParentID, [Name]
FOR XML PATH('Product'), TYPE, ROOT('Products')
)
FOR XML PATH('STEP-ProductInformation'), TYPE;