根据另一个选择的结果进行选择

时间:2018-04-26 03:36:52

标签: sql sql-server tsql

我有这样简单的查询:

    SELECT RoleId FROM Security.UserRoles WHERE UserId = 8

它抛出了值1和2。

我想添加一个条件,如果该选择包含数字2,则执行另一个选择,如下所示:

    SELECT COUNT(O.OrderId) AS TotalItems FROM Store.[Order] O

我尝试这样的事情:

如果没有用另一个选择做一个else子句,我怎么能实现呢?此致

 IF(SELECT RoleId FROM Security.UserRoles WHERE UserId = 8 =2)

但我的语法不正确

3 个答案:

答案 0 :(得分:1)

在您的案例中使用ELSE (IF...ELSE),如下所示:

IF (SELECT SUM(CASE WHEN RoleID = 2 THEN 1 ELSE 0 END) FROM UserRoles WHERE UserId = 8) > 0 
    SELECT COUNT(O.OrderId) AS TotalItems FROM Store.[Order] O
ELSE 
    Query2;

一般语法:

IF Boolean_expression   
     { sql_statement | statement_block }   
[ ELSE   
     { sql_statement | statement_block } ]  

链接到演示:

  

http://sqlfiddle.com/#!18/bf55c/3

答案 1 :(得分:0)

IF(EXISTS(SELECT RoleId FROM Security.UserRoles WHERE UserId = 8 AND RoleId =2))

答案 2 :(得分:0)

使用案例陈述,接近于

SELECT 
( Case When RoleId =2 then
(  SELECT COUNT(O.OrderId) AS TotalItems FROM Store.[Order] O) else 0 end ) count

FROM Security.UserRoles WHERE UserId = 8