views:

1691

answers:

3

Imagine the scene, you're updating some legacy Sybase code and come across a cursor. The stored procedure builds up a result set in a #temporary table which is all ready to be returned except that one of columns isn't terribly human readable, it's an alphanumeric code.

What we need to do, is figure out the possible distinct values of this code, call another stored procedure to cross reference these discreet values and then update the result set with the newly deciphered values:

declare c_lookup_codes for
select distinct lookup_code
from #workinprogress

while(1=1)
begin
    fetch c_lookup_codes into @lookup_code

    if @@sqlstatus<>0
    begin
        break
    end

    exec proc_code_xref @lookup_code @xref_code OUTPUT

    update #workinprogress
    set xref = @xref_code
    where lookup_code = @lookup_code
end

Now then, whilst this may give some folks palpitations, it does work. My question is, how best would one avoid this kind of thing?

NB: for the purposes of this example you can also imagine that the result set is in the region of 500k rows and that there are 100 distinct values of lookupcode and finally, that it is not possible to have a table with the xref values in as the logic in proccodexref is too arcane.

+1  A: 

Unless you are willing to duplicate the code in the xref proc, there is no way to avoid using a cursor.

Stu
+1  A: 

You have to have a XRef table if you want to take out the cursor. Assuming you know the 100 distinct lookup values (and that they're static) it's simple to generate one by calling proccodexref 100 times and inserting the results into a table

David Hayes
A: 

They say, that if you must use cursor, then, you must have done something wrong ;-) here's solution without cursor:

declare @lookup_code char(8)

select distinct lookup_code
into #lookup_codes
from #workinprogress

while 1=1
begin
    select @lookup_code = lookup_code from #lookup_codes

    if @@rowcount = 0 break

    exec proc_code_xref @lookup_code @xref_code OUTPUT

    delete #lookup_codes
    where lookup_code = @lookup_code
end
B0rG