TSQL - Mapping one table to another without using cursor -
i have tables following structure
create table doc( id int identity(1, 1) primary key, documentstartvalue varchar(100) ) create metadata ( documentvalue varchar(100), startdesignation char(1), pagenumber int ) go doc contains id documentstartvalue 1000 id-1 1100 id-5 2000 id-8 3000 id-9 metadata contains documentvalue startdesignation pagenumber id-1 d 0 id-2 null 1 id-3 null 2 id-4 null 3 id-5 d 0 id-6 null 1 id-7 null 2 id-8 d 0 id-9 d 0
what need map metadata.documentvalues doc.id
so result need like
id documentvalue pagenumber 1000 id-1 0 1000 id-2 1 1000 id-3 2 1000 id-4 3 1100 id-5 0 1100 id-6 1 1100 id-7 2 2000 id-8 0 3000 id-9 0
can achieved without use of cursor?
something like, sorry can't test
;with rowlist ( --assign rownums each row... select row_number() on (order id) rownum, id, documentstartvalue doc ), rowpairs ( --this allows pair row previous rows create ranges select r.documentstartvalue start, r.id, r1.documentstartvalue end rowlist r join rowlist r1 on r.rownum + 1 = r1.rownum ) --use ranges join , data select rp.id, m.documentvalue, m.pagenumber rowpairs rp join metadata m on rp.start <= m.documentvalue , m.documentvalue < rp.end
edit: assumes can rely on id-x values matching , being ascending. if so, startdesignation superfluous/redundant , may conflict doc table documentstartvalue
Comments
Post a Comment