【问题标题】:Conditional column name in SQL where clauseSQL where 子句中的条件列名称
【发布时间】:2023-01-02 16:15:10
【问题描述】:

SQL中应该如何处理以下内容? where 子句是什么?

select *
from tbl_A a
inner join tbl_B b on a.pid = b.pid
where #name# like '%@searchText%

但此列 #name# 是基于条件 - (如果 pid 为空,则使用 a.pname 列,否则使用 b.name

【问题讨论】:

    标签: sql sql-server


    【解决方案1】:

    您只需使用常规的 AND/OR 逻辑...

    select *
    from tbl_A a
    left join tbl_B b on a.pid = b.pid
    where (a.pid is null and a.pname like '%' + @SearchText + '%')
    or (a.pid is not null and b.pname like '%' + @SearchText + '%');
    
    1. 您会想要如图所示拆分搜索文本以添加通配符。
    2. 你会想要一个左连接是pid可以为空,即没有匹配。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-08
      • 2014-11-01
      • 1970-01-01
      • 2011-05-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多