views:

45

answers:

1

I have the following CTE SQL

WITH Tasks AS (
    SELECT     TaskID, ParentTaskID, CAST(SortKey AS nChar) AS sort_key
               /*,cast(SortKey as char) as sort_key */
      FROM     oaTasks AS s
      WHERE    (TaskID = 1)
      UNION ALL
      SELECT   s2.TaskID, s2.ParentTaskID
               ,Cast( '0.'+ cast(Tasks_2.sort_key as NCHAR)
                 + '0.' + cast(s2.SortKey as NCHAR) as NCHAR) AS sort_key
               /*,cast(Tasks_2.sort_key +'.'+ cast(s2.SortKey as char) as char)*/
      FROM     oaTasks AS s2
      INNER JOIN Tasks AS Tasks_2
         ON Tasks_2.TaskID = s2.ParentTaskID
)
SELECT  Tasks_1.TaskID, oaTasks.Task, oaTasks.ParentTaskID
        , oaTasks.SortKey,Tasks_1.sort_key
  FROM  Tasks AS Tasks_1
  INNER JOIN oaTasks ON Tasks_1.TaskID = oaTasks.TaskID

In sort_key column I am not getting the desired format which should be like 01, 01.01, 01.01.01 etc. but I'm getting 1, 0.1, 0.1.1. Any suggestion?

+1  A: 

try RIGHT like select RIGHT('00',1,2) gives 01

Harendra
i changed CAST(SortKey AS nChar) to right('0.',SortKey ) and Cast( '0.'+ cast(Tasks_2.sort_key as NCHAR) + '0.' + cast(s2.SortKey as NCHAR) as NCHAR) AS sort_key to right( '0.', Tasks_2.sort_key ) + right('0.' , s2.SortKey) AS sort_key but i am getting error "Types don't match between the anchor and the recursive part in column "sort_key" of recursive query "Tasks"."
Tassadaque
right takes 3 parameters as ist is the appended text, 2nd is actual value and 3 is total length. right('0.',SortKey ) missing 3rd one. try modify ur query accordingly
Harendra
right('0.',SortKey,2 ) gives following error "The right function requires 2 argument(s)."
Tassadaque
yupp!! mistake...split ur string by . like SELECT RIGHT ('00'+ CAST (1 AS varchar), 2)+ '.'+ right('00'+ cast(1 as varchar),2) it will return 01.01
Harendra
thanks for ur help through some modification it is running but for the third level instead of showing 01.01.01 it is showing 01.01 modified line is cast(RIGHT ('00'+ CAST (Tasks_2.sort_key AS varchar), 2)+ '.'+ right('00'+ cast(s2.SortKey as varchar),2) as nvarchar) AS sort_key
Tassadaque
ur query seems limited to second level, let me know exactly how's data storage?
Harendra
i have the scenario as mentioned in the following link and i am following query from here it is self join query taskid is joined to parenttaskid http://forums.devshed.com/firebird-sql-development-61/need-an-inner-order-by-in-a-recursive-cte-654561.html
Tassadaque
hv checked link seems that u can't fixed the length it should be dynamically. second aggument will be the actual length and leading zero as per length
Harendra
Any idea how to achieve i tried to add depth in it as the above link added. Can i relate depth to achieve the desired result
Tassadaque
yes depth will resolve the problem.. try it
Harendra