存储过程的WHERE子句中的条件

时间:2012-03-18 08:32:47

标签: sql sql-server stored-procedures

我有这个存储过程

CREATE PROCEDURE sp     
    @JOB_TYPE INT = NULL ,
    @MODE INT = 0
AS  
    IF @MODE = 0
    BEGIN        
    SELECT     ProjectId , 
               ProjectName ,               
               D3,
               D2,
               D1,
               F0,
               F1,
               F2,
               F3,                         
    FROM       View_A
    WHERE   (JobTypeId = @JOB_TYPE)                                         
    END

    IF @MODE = 1            --PROJECT WITH NO ACTIVITY IN THE LAST TREE MONTH
    BEGIN        
    SELECT     ProjectId, 
               ProjectName,               
               D3,
               D2,
               D1,
               F0,
               F1,
               F2,
               F3,                         
    FROM       View_A
    WHERE   (JobTypeId = @JOB_TYPE) 
                AND D3 = 0
                AND D2 = 0
                AND D1 = 0
    END

正如您所看到的,两个select语句都是相同的,唯一的区别在于WHERE子句,在第二个选择中还有三个条件。

如何将两个select语句连接到WHERE子句中具有条件的语句?

4 个答案:

答案 0 :(得分:4)

我认为这会返回相同的结果(我不太喜欢这种模式,但我现在不能认为100%如何删除它)

SELECT 
    ProjectId , ProjectName, D3, D2, D1, F0, F1, F2, F3,
FROM 
    View_A 
WHERE 
    (JobTypeId = @JOB_TYPE AND 0 = @Mode)
    OR (1 = @Mode AND JobTypeId = @JOB_TYPE AND D3 = 0 AND D2 = 0 and D1 = 0)

答案 1 :(得分:4)

检查一下:

CREATE PROCEDURE sp     
@JOB_TYPE INT = NULL ,
@MODE INT = 0
AS  
WITH myCTE
AS
(
    SELECT     ProjectId , 
               ProjectName ,               
               D3,
               D2,
               D1,
               F0,
               F1,
               F2,
               F3                       
    FROM       View_A
    WHERE   (JobTypeId = @JOB_TYPE)                                         
)
Select * from myCTE
where  (@MODE = 0) OR (@MODE = 1 AND D3 = 0 AND D2 = 0 AND D1 = 0)

答案 2 :(得分:0)

也许它会更清晰:

where JobTypeId = @Job_Type and -- JobTypeId must always match.
  case -- Filter on the appropriate mode.
    when @Mode = 0 then 1 -- All projects.
    when @Mode = 1 and -- No activity in the last three months.
      D3 = 0 and D2 = 0 and D1 = 0 then 1
    else 0
    end = 1

添加过滤器模式更容易,但过度使用可能不是一个好主意。

答案 3 :(得分:0)

USE [数据库名称] GO

如果OBJECT_ID('sp')不为空 - 我认为我们首先需要撤销程序    DROP PROCEDURE sp

创建程序sp
    @Job_Type int = null,@ Mode int = 0; AS
    如果@Mode = 0     开始     SELECT
          Project_Id,[项目名称],D3,D2,D1,F0,F1,F2,F3
    从
          View_A     WHERE
        (JobTypeId = @JOB_TYPE)
    端

IF @MODE = 1            --NULL PROJECTS FOR PREVIOUS THREE MONTHS
Begin        
SELECT     
      ProjectId, [Project Name], D3, D2, D1, F0, F1, F2, F3                        
FROM
      View_A
WHERE   
      (JobTypeId = @JOB_TYPE) 
            AND D3 = 0
            AND D2 = 0
            AND D1 = 0
End