尝试使用switch case语句获取单列数据

时间:2017-11-15 11:29:23

标签: sql-server tsql sql-server-2012 sql-server-2014

我正在尝试根据下面的角色查询表格,但我收到的错误就像这样

  

' ='。

附近的语法不正确

我不确定为什么会收到此错误

下面是我的查询

CREATE procedure [dbo].[getName]            
    @AccountId int,    
    @role varchar(50),
    @Activated_By nvarchar(100)            
AS            
BEGIN           

    SELECT   Name 
    FROM     pass_activationinfo 
    WHERE 
        CASE WHEN @role = 'Admin'
             THEN account_id = @AccountId
             ELSE Activated_By = @Activated_By
        END
END

3 个答案:

答案 0 :(得分:6)

第一个变种

SELECT   Name 
FROM     pass_activationinfo 
WHERE 
        (@role = 'Admin' AND account_id = @AccountId)
    OR (@role <> 'Admin' AND Activated_By = @Activated_By)

第二个变种

SELECT   Name 
FROM     pass_activationinfo 
WHERE 
    CASE
      WHEN @role = 'Admin' AND account_id = @AccountId THEN 1
      WHEN @role <> 'Admin' AND Activated_By = @Activated_By THEN 1
      ELSE 0
    END = 1

答案 1 :(得分:2)

更改案例并改为使用OR

CREATE procedure [dbo].[getName]            
    @AccountId int,    
    @role varchar(50),
    @Activated_By nvarchar(100)            
AS            
BEGIN           

    SELECT   
        Name 
    FROM pass_activationinfo 
    WHERE 
        (
            @role = 'Admin'
            AND
            account_id = @AccountId
         )
         OR
         (
            @role <> 'Admin'
            AND
            Activated_By = @Activated_By
         )


END

答案 2 :(得分:1)

你可以用这个

   SELECT   Name 
    FROM     pass_activationinfo 
    WHERE 
        (( @role = 'Admin'
             and  account_id = @AccountId)
             or Activated_By = @Activated_By)