Search code examples
sqlviewcrystal-reports

Persistent variable in view


I have this issue where I would like to use a variable that only changes under certain conditions...

1 Item1 <parent>
2 Item2 <child>
3 Item3 <child>
4 Item4 <child>
5 Item5 <parent>
6 Item6 <child>

I have a data table that once you select the parent item, it populates the associated child items below it. The problem I have though, is I would like to identify the parent that the child item belongs to - and the only way in the data is the order in which they arrive (ie each child item is the child of the last parent item in the sequence)

If I could use a variable - then I could just assign the value to the variable each time a parent is identified - and print out the value of that variable on each line. Something like this:

1 Item1 <parent> Item1
2 Item2 <child>  Item1
3 Item3 <child>  Item1
4 Item4 <child>  Item1
5 Item5 <parent> Item5
6 Item6 <child>  Item5

So I know which parent each child belongs to. Is there anyway in a view that I can get an output like the one above (I need to use a view as I would like to link the output in a crystal report ultimately)

As a follow up to my comment below ... here's the way I would like the code to work for multiple orders on my system, hopefully it makes sense!

with 
parent_ranges as(
    select SOHNUM_0,ITMREF_0 as ITM, SOPLIN_0, LEAD(SOPLIN_0, 1, NULL) over (order by SOHNUM_0,SOPLIN_0) NX
   from <MY_DB>.SORDERP with (nolock)
 where LINTYP_0 = 6 –Parent
--and SOHNUM_0 = '<My Order Number>'
) 
select case when t1.LINTYP_0 in (6,7,8,9) then isnull(t2.ITM,'?') else 'NO'  end as PARENT_ITEM, t1.LINTYP_0,t1.ITMREF_0   
from <MY_DB>.SORDERP t1 with (nolock)
left join parent_ranges t2 on (t1.SOHNUM_0 = t2.SOHNUM_0 and t1.SOPLIN_0 >=  t2.SOPLIN_0 and ((t1.SOPLIN_0 < t2.NX) OR t2.NX IS NULL))
where t1.SOHNUM_0 = '<My Order Number>'

Can you see a way that I don't need to have the --and SOHNUM_0 = '' line in the view?


Solution

  • From sql-server 2012 you can use LEAD function:

    ;with 
    parent_ranges as(
        select *, LEAD(id, 1, NULL) over (order by id) NX
        from @tbl
        where kind = 'parent'
    ) 
    select T1.*, T2.Item PARENT_ITEM
    from @tbl t1
    left join parent_ranges t2 on t1.id >= t2.ID and (t1.id < t2.NX OR t2.NX IS NULL)