在where语句中使用if

时间:2019-08-05 08:09:39

标签: sql sql-server sql-server-2017

我有4张桌子:

  1. Table_op_type
  2. Table_maintenancetype
  3. Table_repair_time
  4. Table_repair_type

每个表都有一列可以为真或为假,当我选择Table_maintenancereport时,我有一个Table_maintenancereport有很多列,而在Table_maintenancereport外键中有4列是从4向上表给出的并且每张表中的一行都是正确的代码,可以正常工作,但是当表中返回多于一行时,就会出现此错误。

  

子查询返回了多个值。当子查询遵循=,!=,<,<=,>,> =或将子查询用作表达式时,不允许这样做。

我该如何解决?

我的代码是:

SELECT *
FROM Table_maintenancereport
WHERE mtypeid IN (IIF(@smtype = 1, (SELECT Table_maintenancetype.id FROM Table_maintenancetype WHERE enable_search = 1), mtypeid))
  AND op_typeid IN (IIF(@sop IN (1), (SELECT Table_op_type.id FROM Table_op_type WHERE enable_search = 1), op_typeid))
  AND repaire_timeid IN (IIF(@stime IN (1), (SELECT Table_repair_time.id FROM Table_repair_time WHERE enable_search = 1), repaire_timeid))
  AND repaire_typeid IN (IIF(@stype = 1, (SELECT Table_repair_type.id FROM Table_repair_type WHERE enable_search = 1), repaire_typeid));

3 个答案:

答案 0 :(得分:1)

如果我正在解释您要正确执行的操作:

SELECT *
FROM Table_maintenancereport mr
LEFT OUTER JOIN Table_maintenancetype mt ON mr.mtypeid = mt.id AND enable_search = 1
LEFT OUTER JOIN Table_op_type ot ON mr.op_typeid = ot.id AND enable_search = 1
LEFT OUTER JOIN Table_repair_time rt ON mr.repaire_timeid = rt.id AND enable_search = 1
LEFT OUTER JOIN Table_repair_type rty ON mr.repaire_typeid = rty.id AND enable_search = 1
WHERE (ISNULL(@smtype,-1) != 1 OR mt.id IS NOT NULL)
AND (ISNULL(@sop,-1) != 1 OR ot.id IS NOT NULL)
AND (ISNULL(@stime,-1) != 1 OR rt.id IS NOT NULL)
AND (ISNULL(@stype,-1) != 1 OR rty.id IS NOT NULL)

因此,对于每个@variable,如果将其设置为1,则对应的字段必须是要在输出中显示的启用搜索的ID之一。如果变量未设置为1,则不会过滤相应的字段。

答案 1 :(得分:1)

您需要修复where条件。您可以使用基本逻辑运算符执行此操作。集不能由iif()case()表达式返回。

所以:

WHERE (@smtype <> 1 OR
       mtypeid IN (SELECT Table_maintenancetype.id FROM Table_maintenancetype WHERE enable_search = 1)
      ) AND
      (@sop <> 1 OR
       op_typeid IN (SELECT Table_op_type.id FROM Table_op_type WHERE enable_search = 1)
      ) AND
      (@stime <> 1 OR
       repaire_timeid IN (SELECT Table_repair_time.id FROM Table_repair_time WHERE enable_search = 1)
      ) AND
      (@stype <> 1 OR
       repaire_typeid IN (SELECT Table_repair_type.id FROM Table_repair_type WHERE enable_search = 1)
      );

答案 2 :(得分:0)

也许您可以在where子句中使用CASE WHEN语句,例如:

   select
    *
from
    Table_maintenancereport
where
    case
        when @smtype = 1 then mtypeid in (
            select Table_maintenancetype.id
        from
            Table_maintenancetype
        where
            enable_search = 1)
        else mtypeid = mtypeid end

    ....