TSQL - 让它变得更好

时间:2010-05-11 01:41:37

标签: tsql optimization

我有以下TSQL,传入了3个ID(@ Entid,@ DeptID和@CityID),它们都可以为NULL,或者任何一个都可以为NULL。请参阅以下方案:


-- 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


问题:有没有更好的方法(或者我可以做任何事情,如果没有IF ... ELSE条件?

1 个答案:

答案 0 :(得分:1)

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

一些常见的是:
 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