15 July 2011

Rinumerare le righe ad ogni cambio della chiave di testata

Nel caso di una tabella di righe, voglio rinumerare il prog ad ogni cambio di id:

-- CREO TABELLA DELLE RIGHE
declare @tmp table 
(
	  id int
	, prog int 
	, primary key (id,prog)
)


-- RIEMPIO CON VALORI 
insert @tmp select 1, 11
insert @tmp select 2, 22
insert @tmp select 2, 33
insert @tmp select 3, 44


--select * from @tmp


-- RINUMERO A PARTIRE DA 1 (ALTRIMENTI NON FUNZIONA!!)
declare @p int;set @p = 0
	
UPDATE	@tmp
SET		@p = prog = @p + 1



--select * from @tmp



-- TABELLA CON I NUOVI prog
declare @num as table
(
	  id int
	, prog int
	, oldProg int
	, primary key (id,prog)
)



-- MAGIA!!!!
insert @num
select
    T.id,
    T.prog - n,
    T.prog 
from
    @tmp T left join 
    (
        select 
            T.id, 
            count(distinct  T2.prog ) as n
        from 
            @tmp T left join 
            @tmp T2 on 
                T2.id < T.id
        group by
            T.id
    ) as P    on
        T.id=P.id


select * from @num


-- AGGIORNA NUOVI prog
update	t
set		t.prog = n.prog
from	@tmp t inner join 
		@num n on
			t.id = n.id
		and t.prog = n.oldProg
		


select * from @tmp

Trovato nel cervello del Faro.