Bonjour,

Les boucles If...THEN ne marchent-elles pas en SQL ?
Ma requete veut que, à chaque fois qu'on insère une cotisation, la réserve est automatiquement recalculée en prenant la réserve de l'année précédente + la nouvelle cotisation. Cependant, lorsqu'une personne cotise pour la première fois, il ne sait pas aller chercher la réserve de l'année passée, vu qu'elle n'existe pas. Donc j'aimerais introduire un if (voir fin du code), mais cela ne marche pas.

Merci d'avance pour votre aide précieuse !

Christophe


Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
ALTER TRIGGER [dbo].[Insert_ASS_Cotisation]
   ON  [dbo].[ASS_COTISATION]
   AFTER INSERT
AS 
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
 
	--Déclaration des variables.
	DECLARE @CodeSabam char(10)
	DECLARE @Year char(4)
	DECLARE @montantcot float
	DECLARE @PBforf float
	DECLARE @PBprop float
	DECLARE @ResCot float
	DECLARE @ResPBforf float
	DECLARE @ResPBprop float
 
	--Assignation d'une valeur aux variables.
	SET @CodeSabam = (SELECT CodeSabam FROM INSERTED)
	SET @Year = (SELECT Year FROM INSERTED)
	SET @montantcot=(select [Cotisation] from dbo.[ASS_COTISATION] where ([CodeSabam] = @CodeSabam AND [Year] = @Year))
	SET @PBforf=(select [PBForfaitaire] from dbo.[ASS_COTISATION] where ([CodeSabam] = @CodeSabam AND [Year] = @Year))
	SET @PBprop=(select [PBProportionnel] from dbo.[ASS_COTISATION] where ([CodeSabam] = @CodeSabam AND [Year] = @Year))
	SET @ResCot=(select [Cotisation] from dbo.[ASS_RESERVE] where ([CodeSabam] = @CodeSabam AND [Year] = @Year - 1))
	SET @ResPBforf=(select [PBForfaitaire] from dbo.[ASS_RESERVE] where ([CodeSabam] = @CodeSabam AND [Year] = @Year - 1))
	SET @ResPBprop=(select [PBProportionnel] from dbo.[ASS_RESERVE] where ([CodeSabam] = @CodeSabam AND [Year] = @Year - 1))
 
	--Insertion du nouveau montant de réserve.
	IF @ResCot IS NULL THEN
	INSERT INTO [dbo].[ASS_RESERVE] ([CodeSabam], [Year] ,[Cotisation],[PBForfaitaire],[PBProportionnel]) VALUES(@CodeSabam ,@Year ,@montantcot,@pbforf,@pbprop)
	ELSE
	INSERT INTO [dbo].[ASS_RESERVE] ([CodeSabam], [Year] ,[Cotisation],[PBForfaitaire],[PBProportionnel]) VALUES(@CodeSabam ,@Year ,@ResCot + @montantcot,@ResPBforf + @pbforf,@ResPBprop + @pbprop)
	END IF
 
END
Voici le message d'erreur:

Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
Msg 156, Level 15, State 1, Procedure Insert_ASS_Cotisation, Line 35
Incorrect syntax near the keyword 'THEN'.
Msg 156, Level 15, State 1, Procedure Insert_ASS_Cotisation, Line 37
Incorrect syntax near the keyword 'ELSE'.
Msg 156, Level 15, State 1, Procedure Insert_ASS_Cotisation, Line 41
Incorrect syntax near the keyword 'END'.