ThallForms
ThallForms

Reputation: 87

If statement with 3 conditions SQL

I am trying to do an IF statement in SQL with 3 conditions but when I try to display the message, it displays all 3 messages. How can I end the if statement once one of these conditions is true?

IF( @QuantiteStock > 100) 
    SET @QuantiteStock = @QuantiteStock;
    PRINT  @NomProduit + ' n`a pas été touché.' ;


IF(@QuantiteStock  >= 10 AND @QuantiteStock <= 100) 
    SET @QuantiteStock  = @QuantiteStock *1.25;
    PRINT @NomProduit + ' a été augmenté à ' + CONVERT(VARCHAR(20),@QuantiteStock) ;



    IF( @QuantiteStock < 10) 
        SET @QuantiteStock = 50;
    PRINT @NomProduit + ' a été augmenté à 50' ;
    end

Upvotes: 0

Views: 5366

Answers (2)

Jodrell
Jodrell

Reputation: 35726

On its own IF applies only to the next statement, do this instead,

IF( @QuantiteStock > 100) BEGIN
    SET @QuantiteStock = @QuantiteStock;
    PRINT  @NomProduit + ' n`a pas été touché.';
END

IF(@QuantiteStock  >= 10 AND @QuantiteStock <= 100) BEGIN
    SET @QuantiteStock  = @QuantiteStock *1.25;
    PRINT @NomProduit + ' a été augmenté à '
            + CONVERT(VARCHAR(20),@QuantiteStock);
END

IF( @QuantiteStock < 10) BEGIN
    SET @QuantiteStock = 50;
    PRINT @NomProduit + ' a été augmenté à 50';
END

The IF only applies to the next block or group. If you don't group statements with BEGIN and END then they will each be separate blocks or groups.

BEGIN and END group the statements between them into a block.


Since your conditions are mutually exclusive you can chain them to avoid unnecessary processing.

IF( @QuantiteStock > 100) BEGIN
    SET @QuantiteStock = @QuantiteStock;
    PRINT  @NomProduit + ' n`a pas été touché.';
END
ELSE IF(@QuantiteStock  >= 10 AND @QuantiteStock <= 100) BEGIN
    SET @QuantiteStock  = @QuantiteStock *1.25;
    PRINT @NomProduit + ' a été augmenté à '
            + CONVERT(VARCHAR(20),@QuantiteStock);
END ELSE BEGIN
    SET @QuantiteStock = 50;
    PRINT @NomProduit + ' a été augmenté à 50';
END

Upvotes: 0

Alex K.
Alex K.

Reputation: 175876

For more than one line you must use begin / end else everything after the first line is not conditional.

IF( @QuantiteStock > 100) BEGIN
    SET @QuantiteStock = @QuantiteStock;
    PRINT  @NomProduit + ' n`a pas été touché.' ;
END

So:

IF( @QuantiteStock > 100) BEGIN
    SET @QuantiteStock = @QuantiteStock;
    PRINT  @NomProduit + ' n`a pas été touché.' ;
END 
ELSE IF (...) BEGIN
    ...
END
ELSE BEGIN
    ...
END

Upvotes: 2

Related Questions