i'm working on a stored procedure in TSQL. select * from @tempcostings gives stages in a comma seperated list. How can I split these into columns as the amount of stages is dynamic.
I see there are various examples using string_split and cross apply but cannot see how to apply this. Image below shows my table and what I am trying to achieve.
Trying this put getting the error Cannot find either column "Prod_Attributes" or the user-defined function or aggregate "Prod_Attributes.value", or the name is ambiguous.
;WITH cte (PK, product,standardcost,currentcost,variance,stages)
AS
(
SELECT
[PK],
[product],
[standardcost],
[currentcost],
[variance],
CONVERT(XML,'<Product><Attribute>'
+ REPLACE([stages],',', '</Attribute><Attribute>')
+ '</Attribute></Product>') AS Prod_Attributes
FROM @tempcostings2021
)
SELECT
[PK],
[product],
[standardcost],
[currentcost],
[variance],
Prod_Attributes.value('/Product[1]/Attribute[1]','varchar(25)') AS [Stage1],
Prod_Attributes.value('/Product[1]/Attribute[2]','varchar(25)') AS [Stage2],
Prod_Attributes.value('/Product[1]/Attribute[3]','varchar(25)') AS [Stage3],
Prod_Attributes.value('/Product[1]/Attribute[4]','varchar(25)') AS [Stage4]
FROM cte


string_splitis definitely not an answer). They all seem to point at this approach: jahaines.blogspot.com/2009/06/… See if you can apply the approach as explained in the link and post back if you have problems