• I think I see it now:

    create table test222(sid bigint, scode nvarchar(50), parentid bigint, sname nvarchar(50));

    insert into test222 values (1, '2323', 0, 'iam a boy');

    insert into test222 values (2, '23231000', 1, 'boy');

    insert into test222 values (3, '23232', 1, 'boo');

    insert into test222 values (4, '232321', 3, 'bo');

    insert into test222 values (5, '23232110', 4, 'boyy');

    insert into test222 values (6, '23232190', 4, 'gril');

    insert into test222 values (7, '232329', 3, 'body');

    insert into test222 values (8, '23232910', 7, 'girll');

    insert into test222 values (9, '23232990', 7, 'boy');

    insert into test222 values (10, '23233000', 1, 'bo');

    insert into test222 values (11, '232390', 1, 'nh');

    insert into test222 values (12, '23239010', 10, 'ui');

    insert into test222 values (13, '23239020', 10, 'dert');

    insert into test222 values (14, '23239030', 10, 'hyui');

    insert into test222 values (15, '23239040', 10, 'nji');

    insert into test222 values (16, '23239090', 10, 'vfr');

    select * from dbo.test222;

    with basedata as (

    select

    [sid],

    scode,

    parentid,

    sname,

    sortkey = cast([sid] as varbinary(max))

    from

    dbo.test222

    where

    parentid = 0

    union all

    select

    t2.[sid],

    t2.scode,

    t2.parentid,

    t2.sname,

    sortkey = bd.sortkey + cast(t2.[sid] as varbinary(max))

    from

    basedata bd

    inner join dbo.test222 t2

    on (bd.sid = t2.parentid)

    )

    select * from basedata order by sortkey;

    -- d r o p table dbo.test222; -- remove the -- and the spaces in the word drop. Can't post the actual statement for some reason.