c# - if条件内的sql select语句

标签 c# sql-server tsql if-statement

我想创建如下语句:

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 中可能吗,还是我的想法不正确?

最佳答案

您需要使用 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

如果您可以展示一些您希望这些实际陈述是什么的示例,我可以提供更具体的答案。

关于c# - if条件内的sql select语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15256404/

相关文章:

javascript - 准备好的语句未在带有 mssql 的 Node js 中执行

sql-server - TSQL:按周对客户订单进行分组

sql - 从 SQL Server 2008 中的两个表中检索独占记录

sql-server - 获取当前 Sp 参数和值 - (类似反射)?

c# - 如果原始表为空,则从另一个表中选择

sql - 在 WHERE 子句中引用列别名

c# - 在 Store App 中使用 MVVM 进行页面导航

c# - 为什么我的中继器会出现切换问题?

c# - String.Format 函数不起作用

c# - 从数据表中选择列并将其再次转换为数据表