TSQL WHERE基于Temp Table的子句

时间:2015-04-20 15:58:27

标签: sql-server stored-procedures sql-server-2012

我有一个大型查询,用于根据用户填写的过滤器表单为报表提取数据。他们可以选择诸如地点,部门和主管之类的东西。

我目前正在做的是,如果他们选择All作为选项而不是选择一个特定的位置,我有一个临时表,其中包含我所做的WHERE IN()子句的所有位置。

我正在尝试为我的主管搜索选项做类似的事情。用户不必选择主管进行搜索,在这种情况下,我需要它忽略AND子句的WHERE部分。

如果临时表@sourceLeaderEmps不包含任何记录,则需要忽略下面代码AND b.MgrQID IN (SELECT DISTINCT QID FROM @sourceLeaderEmps)中的最后一行。

有没有简单的方法可以做到这一点?

WHERE  B.[ArchibusLocationName] IN (SELECT location
                                        FROM   @tmLocations)
           AND C.[ArchibusLocationName] IN (SELECT location
                                            FROM   @subLocations)
           AND B.[DepartmentDesc] IN (SELECT department
                                      FROM   @tmDepartments)
           AND C.[DepartmentDesc] IN (SELECT department
                                      FROM   @subDepartments)
           AND DATEDIFF(second, '19700101', CAST (CONVERT (DATETIME, A.[escalationCreated], 121) AS INT)) >= @startDate
           AND DATEDIFF(second, '19700101', CAST (CONVERT (DATETIME, A.[escalationCreated], 121) AS INT)) <= @endDate
           AND a.[PREVENTABLE] IN (SELECT PREVENTABLE
                                   FROM   @preventable)
           AND b.MgrQID IN (SELECT DISTINCT QID FROM @sourceLeaderEmps) 

1 个答案:

答案 0 :(得分:0)

创建“计数”变量。

declare @sourceLeaderEmpsCOUNT int

保湿

select @sourceLeaderEmpsCOUNT = count(*) from @sourceLeaderEmps

现在做一个OR子句

Where
/* other stuff */
and
((   ( @sourceLeaderEmpsCOUNT = 0) OR  (/* your in or exists clause here */  )   ))

这样的事情:

    declare @sourceLeaderEmpsCOUNT int
    select @sourceLeaderEmpsCOUNT = count(*) from @sourceLeaderEmps



WHERE  B.[ArchibusLocationName] IN (SELECT location
                                        FROM   @tmLocations)
           AND C.[ArchibusLocationName] IN (SELECT location
                                            FROM   @subLocations)
           AND B.[DepartmentDesc] IN (SELECT department
                                      FROM   @tmDepartments)
           AND C.[DepartmentDesc] IN (SELECT department
                                      FROM   @subDepartments)
           AND DATEDIFF(second, '19700101', CAST (CONVERT (DATETIME, A.[escalationCreated], 121) AS INT)) >= @startDate
           AND DATEDIFF(second, '19700101', CAST (CONVERT (DATETIME, A.[escalationCreated], 121) AS INT)) <= @endDate
           AND a.[PREVENTABLE] IN (SELECT PREVENTABLE
                                   FROM   @preventable)
           AND ((  (@sourceLeaderEmpsCOUNT=0) OR (b.MgrQID IN (SELECT DISTINCT QID FROM @sourceLeaderEmps) ) ))