1

我想创建如下语句:

if (select statement1 returns rows){
   select statement2
}
else {
  select statement3
}

if语句是更大查询的一部分

   select from products where p.id in (
        if (select statement1 returns rows){
           select statement2
       }
       else {
        select statement3
      }

这在 SQL Server 中是否可行,还是我的想法不正确?

4

4 回答 4

3

您需要使用EXISTS和的组合CASE..END

select *
from products
where p.id in (
  case when (exists ( <statement1> ))
    then ( <statement2> )
    else ( <statement3> )
  end
)

<statement1>可能在哪里:SELECT * FROM Customer WHERE Id = 123

<statement2>可能:SELECT MIN(field) FROM someTable

<statement3>可能:SELECT 0 as DefaultValue

如果您可以展示一些您想要这些实际陈述的示例,我可以提供更具体的答案。

于 2013-03-06T19:37:35.353 回答
1

实际上,出于性能考虑,SQL 更加严格。您的查询看起来更像这样:

select *
from products
where  1 = case when (exists ( <statement1> ))
              then case when p.id in ( <statement2> ) then 1 else 0 end
              else case when p.id in ( <statement3> ) then 1 else 0 end
           end
于 2013-03-06T19:44:40.150 回答
1

由于您正在检查相同的id存在,我认为您可以在UNION这里做一个。

select *
from products 
where p.id in  (select id from table1
                union 
                select id from table2)
于 2013-03-06T19:47:59.487 回答
1

我建议在您的两个条件之间使用 UNION 来帮助避免性能问题......并且可能也更容易阅读。

    SELECT FROM products p
    WHERE EXISTS (SELECT STATEMENT1)
    AND EXISTS (SELECT STATEMENT2 s2 WHERE s2.p_id = p.id)
    UNION
    SELECT FROM products p
    WHERE NOT EXISTS (SELECT STATEMENT1)
    AND EXISTS (SELECT STATEMENT3 s3 WHERE s3.p_id = p.id)    

Depending on the nature of the statements, you might be able to leave off the Not Exists in the second select.

于 2013-03-06T19:55:53.430 回答