Skip to content
Advertisement

Use multiple IF condition to set variable

I receive parameters to stored procedure:

          @BDOnly                       BIT
        , @CDOnly                       BIT
        , @PPOOnly                      BIT
        , @FBOMOnly                     BIT 

Then depending of this variables I do an IF condition to set other variables like:

  DECLARE @IsBDChecked   VARCHAR(10)
        , @IsCDChecked   VARCHAR(10)
        , @IsPPOChecked  VARCHAR(10)
        , @IsFBOMChecked VARCHAR(10)

    IF(@BDOnly = 1)
    BEGIN
       SET @IsBDChecked = 'Test1'
    END
    IF(@CDOnly = 1)
    BEGIN
       SET @IsCDChecked = 'Test2'
    END
    IF(@PPOOnly = 1)
    BEGIN
       SET @IsPPOChecked = 'Test3'
    END
    IF(@FBOMOnly = 1)
    BEGIN
       SET @IsFBOMChecked = 'Test4'
    END

Is that the best way to do this? or can I do better?

Advertisement

Answer

You can do the logic all inside one statement:

SELECT @IsBDChecked = (CASE WHEN @IsBDChecked = 1 THEN 'Test1' END),
       @IsCDChecked = (CASE WHEN @IsCDChecked = 1 THEN 'Test2' END),
       @IsPPChecked = (CASE WHEN @IsPPOChecked = 1 THEN 'Test3' END),
       @IsFBOMChecked = (CASE WHEN @IsFBOMChecked = 1 THEN 'Test4' END)
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement