venerdì 22 aprile 2011

Esempio Stored Procedure in Sql Server

-- semplice procedura che riporta sul campo AGENTE di MOVCO il campo CODAG di CFVEN relativo allo stesso cliente 



ALTER PROCEDURE [dbo].[Agg_mov_agenti] 
-- Add the parameters for the stored procedure here
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

declare @sottoconto char(10)
declare @agente char(5)

DECLARE age_cursor CURSOR FOR 
    select DISTINCT SOTTOCONTO,CODAG
 FROM MOVCO,CFVEN
      WHERE SOTTOCONTO=CODCF
 AND TIPO='C'
 AND (
 (AGENTE IS NULL) OR
 ( AGENTE <> CODAG)
      )


    OPEN age_cursor 


    FETCH NEXT FROM age_cursor 
     INTO @sottoconto,@agente
     
    WHILE @@FETCH_STATUS = 0 
    BEGIN 
     UPDATE MOVCO SET AGENTE=@agente WHERE SOTTOCONTO=@sottoconto


     FETCH NEXT FROM age_cursor 
     INTO @sottoconto,@agente
    
    END 


CLOSE age_cursor 
DEALLOCATE age_cursor 


    
END