Option based on @onaiggac (you can use its data :-))
;WITH CTE (id, id_parent, name_product, LEVEL, SORTKEY) AS ( SELECT id, id_parent, name_product, 1, CAST(ROW_NUMBER() OVER (ORDER BY name_product) AS VARBINARY(MAX)) FROM @tab where id_parent is null
Trick used here
ROW_NUMBER() OVER (ORDER BY name_product)
make an "internal" order. As with @onaiggac, this is then binary compiled in varbinary(max)
CAST(ROW_NUMBER() OVER (ORDER BY name_product) AS VARBINARY(MAX))
which is then recursively supplemented ...
C.SORTKEY + CAST(ROW_NUMBER() OVER (ORDER BY t.name_product) AS VARBINARY(MAX))
Note that ROW_NUMBER() will return bigint ... you can send it to int before directing it to varbinary(max) , e.g.
CAST(CAST(ROW_NUMBER() OVER (ORDER BY name_product) AS INT) AS VARBINARY(MAX))
if you really want ... I don't think it is necessary if your tree is really deep.
source share