【问题标题】:Re-factor simple SQL statement with WHERE clause使用 WHERE 子句重构简单的 SQL 语句
【发布时间】:2015-07-26 11:21:51
【问题描述】:

我觉得必须有更有效的方法来做到这一点。我想允许调用者拉出所有书籍,或未隐藏的书籍(见下文)

if isnull(@ShowHiddenBooks, 0) = 1
    begin
        select
            (long list of fields)
        from
            MyTable
        where
            MyField = @SomeField
    end
else
    begin
        select
            (long list of fields)
        from
            MyTable
        where
            MyField = @SomeField and
            IsHidden = 0    
    end

有什么想法吗?

谢谢!

【问题讨论】:

    标签: c# sql asp.net .net sql-server


    【解决方案1】:
    Select *
    from MyTable
    where MyField = @SomeField and
    (isHidden = 0 or @showHiddenBooks = 1)
    

    【讨论】:

    • 当@showHiddenBooks 为空时考虑到此失败。
    • @Steve,如果为空,则不会为 1
    • @ps2goat SQL的语义与C#不同,null = 1为真
    • @Steve 不,不是。运行这条语句:select case when null = 1 then 'true' else 'false' end你会看到结果是'false'
    • @Steve,你错了,null = 1 不成立,未知!更何况 null = null 是未知数!
    【解决方案2】:

    这相当于:

     select (long list of fields)
        from
            MyTable
        where
            MyField = @SomeField and
            (IsHidden = 0 or isnull(@ShowHiddenBooks, 0) = 1)
    

    【讨论】:

      猜你喜欢
      • 2018-09-06
      • 1970-01-01
      • 2020-03-26
      • 2011-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-16
      相关资源
      最近更新 更多