代码之家  ›  专栏  ›  技术社区  ›  user319353

TSQL-让它变得更好

  •  1
  • user319353  · 技术社区  · 14 年前

    
    -- Very Narrow (all IDs are passed in)
    IF(@EmpID IS NOT NULL AND @DeptID IS NOT NULL AND @CityID IS NOT NULL)
       BEGIN    
          SELECT
             e.EmpName 
             ,d.DeptName
             ,c.CityName
          FROM
             Employee e WITH (NOLOCK)
             JOIN Department d WITH (NOLOCK) ON e.deptid = d.deptid
             JOIN City c WITH (NOLOCK) ON e.CityID = c.CityID
          WHERE 
             e.EmpID = @EmpID
       END
    -- Just 2 IDs passed in
    ELSE IF(@DeptID IS NOT NULL AND @CityID IS NOT NULL)
       BEGIN
          SELECT
             e.EmpName 
             ,d.DeptName
             ,NULL AS [CityName]
          FROM
             Employee e WITH (NOLOCK)
             JOIN Department d WITH (NOLOCK) ON e.deptid = d.deptid
             JOIN City c WITH (NOLOCK) ON e.CityID = c.CityID
          WHERE 
             d.deptID = @DeptID
       END
    -- Very Broad (just 1 ID passed in)
    ELSE IF(@CityID IS NOT NULL)
       BEGIN
          SELECT
             e.EmpName 
             ,NULL AS [DeptName]
             ,NULL AS [CityName]
          FROM
             Employee e WITH (NOLOCK)
             JOIN Department d WITH (NOLOCK) ON e.deptid = d.deptid
             JOIN City c WITH (NOLOCK) ON e.CityID = c.CityID
          WHERE 
             c.CityID = @CityID
       END
    -- None (Nothing passed in)
    ELSE 
       BEGIN
          SELECT
             NULL AS [EmpName]
             ,NULL AS [DeptName]
             ,NULL AS [CityName]
       END
    
    
    

    问题:有没有更好的方法(或者具体来说,我可以做任何事情没有如果…其他条件)?

    1 回复  |  直到 13 年前
        1
  •  1
  •   Community Dunja Lalic    7 年前

    有很多方法可以做到这一点。关键是生成一个将使用索引的查询。


    x = @x OR @x IS NULL
    Using IF statements
    eliminate nulls by using min and max values
    Dynamic SQL
    OPTION (RECOMPILE), on certain versions of SQL Server 2008

    此链接将解释这些以及其他几个方面: http://www.sommarskog.se/dyn-search.html

    看看以前的类似问题:
    Optimal search queries

    Implementing search functionality with multiple optional parameters against database table

    在特定的代码示例中,可能需要添加dbo。或者每个表名上的任何模式,这样每个用户都不会在缓存中获得自己的版本请参见: http://www.sommarskog.se/dynamic_sql.html#queryplans

    您可能还需要担心参数嗅探,请参阅: http://www.sommarskog.se/dyn-search-2005.html#OR_ISNULL