Вопрос

I am being asked to produce an SSRS 2008 report that will print parts labels. The parts department wants to be able to choose which part numbers on an order need a label for each piece. For instance, if the customer orders 50 bolts then they want a label printed for 50 but if they order 5 tires they want a label printed for each tire. The choosing is not the issue, the issue is writing the query so that I get one result set for SSRS. I am using SQL Server 2008 R2.

My query:

declare @pmf varchar(4), @pro varchar(25), @desc varchar(50), @qty decimal(15, 2),    @count int
declare csr cursor for
select opl.psk_pmf_id, 
       opl.psk_pro_id, 
       case when charindex(';', pdi.pdi_desc) = 0 then pdi.pdi_desc 
            else SUBSTRING(pdi.pdi_desc, 1, CHARINDEX(';', pdi.pdi_desc) - 1) end, 
       convert(integer, opl.opl_q_all)
from oph inner join opl on oph.oph_id = opl.oph_id
         inner join pdi on opl.psk_pmf_id = pdi.pmf_id and opl.psk_pro_id = pdi.pro_id
where oph.oph_doc_id = 'C1216974'
order by opl.psk_pmf_id, opl.psk_pro_id
open csr
fetch next from csr into @pmf, @pro, @desc, @qty
while @@FETCH_STATUS = 0
begin
        if rtrim(@pmf) + rtrim(@pro) in ('CAT0308144', 'CAT1P0808')
        begin 
        select @pmf as pmf, @pro as pro, @desc as dscr, cast(@qty as integer) as qty 
        fetch next from csr into @pmf, @pro, @desc, @qty
    end
    else
        set @count = 1
        while @count <= @qty
        begin
            select @pmf as pmf, @pro as pro, @desc as dscr, 1 as qty
            set @count = @count + 1
        end
        fetch next from csr into @pmf, @pro, @desc, @qty
end
close csr
deallocate csr

This gives me the correct data. Ignore if rtrim(@pmf) + rtrim(@pro) in ('CAT0308144', 'CAT1P0808'), that is just there to confirm that the correct number of rows is returned. The problem is that this produces 255 rows of one record each. What I want is one dataset with 255 rows. I have tried selecting into a temp table which of course didn't work. Then I thought about creating a table to insert into but I would have to truncate it each time and if two users are using this at the same time it would get ugly.

Advice?

Это было полезно?

Решение

You can declare a table variable or create a temp table before your cursor, insert into (not select into) it for each iteration of the cursor, then select from it after the cursor.

However, you may be able to accomplish this much faster and simpler, and without the need for a cursor by using a cross join and a helper table - I'd suggest looking into that.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top