使用多个IF条件设置变量

时间:2019-04-02 23:07:35

标签: sql sql-server tsql

我收到存储过程的参数:

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

然后根据此变量,我执行IF条件来设置其他变量,例如:

  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

这是最好的方法吗?还是我可以做得更好?

1 个答案:

答案 0 :(得分:2)

您可以在一条语句中进行全部逻辑处理:

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)