cancel
Showing results for 
Search instead for 
Did you mean: 
Read only

Use this SQL with Sybase

Former Member
10,155

I have a good working sql that works in sql server. The logical computation calculates how many lengths will fit a barrel. Maximum capacity per drum is 14300 meters. My question is how I can get this to work with Sybase.

Declare @tblLength table (num int, qty int, unit varchar(20))

insert @tblLength
values
(2,2500,''),
(1,3800,''),
(1,4200,''),
(1,6500,''),
(1,8300,'')

;with cte as
(
select i=1, qty, unit from @tblLength where num >= 1
union all
select i=i+1, t.qty, t.unit from @tblLength t, cte where t.qty=cte.qty and t.unit = cte.unit and t.num >= i+1
),
cte2 as
(
select *, id=row_number() over (order by qty desc) from cte
),
cte3 as
(
select j=1, qty, unit, id, tot=qty, drum=1 from cte2 where id = 1
union all
select j=j+1, cte2.qty, cte2.unit, cte2.id,
tot=case when cte3.tot+cte2.qty > 14300 then cte2.qty else cte3.tot+cte2.qty end,
drum=case when cte3.tot+cte2.qty > 14300 then cte3.drum + 1 else cte3.drum end
from cte2,cte3 where cte2.id = j+1
)
select drum, qty, unit from cte3
View Entire Topic
Former Member
0 Likes

I just went through the same exercise as Breck and I concur that the main issue arises with the inclusion of cte3.

I suspect this is due to the documented restriction:

"References to other recursive common table expressions cannot appear within 
 the definition of recursive common table expressions as recursive common table 
 expressions cannot be mutually recursive."


In the case of this query, the definitions of cte and cte3 are both recursive (common table expressions), so that would seem to be the most likely candidate for the invalidness of cte3.

I don't know what the best approach is here; one could possibly inject a layer like a stored procedure or temporary stored procedure to isolate out the references ... but that seems inefficient.

Former Member
0 Likes

Ok. Can I do this SQL in a different way but with the same functionality?