if  not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Badge]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE [dbo].[Badge] (
	[codbadge] [char] (50) COLLATE Latin1_General_CI_AS NOT NULL ,
	[idcliente] [int] NOT NULL ,
	[dataemissione] [datetime] NOT NULL ,
	[saldo] [decimal](10, 2) NULL ,
	[datasaldo] [datetime] NULL 
) ON [PRIMARY]
GO

if  not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[BadgeRighe]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE [dbo].[BadgeRighe] (
	[codbadge] [char] (50) COLLATE Latin1_General_CI_AS NOT NULL ,
	[idmovimento] [bigint] NOT NULL ,
	[dataMovimento] [datetime] NOT NULL ,
	[ImportoMovimento] [decimal](10, 2) NOT NULL ,
	[Causale] [char] (50) COLLATE Latin1_General_CI_AS NULL ,
	[IdDocRiferimento] [bigint] NULL 
) ON [PRIMARY]
GO

IF EXISTS (SELECT name FROM sysobjects
      WHERE name = 'TRI' AND type = 'TR')
   DROP TRIGGER TRI
GO

CREATE TRIGGER [TRI] ON [dbo].[BadgeRighe] 
FOR INSERT, UPDATE, DELETE 
AS

DECLARE @Last CHAR(50)
SELECT @Last = codbadge FROM deleted
SELECT @Last = codbadge FROM inserted

UPDATE [dbo].[Badge] SET SALDO = ( 
SELECT SUM(IMPORTOMOVIMENTO) FROM [dbo].[BadgeRighe] WHERE CODBADGE = @Last 
)
 WHERE CODBADGE = @Last


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

