2012-03-05 66 views
2

我已存儲過程:如果情況在存儲過程

ALTER PROCEDURE [dbo].[proc_GetApplicationByCostCentreId] 
( 
    @CostCentreId TINYINT, 
    @DepartmentId INT = NULL, 
    @IsActive BIT = NULL 
) 
AS 

BEGIN 
    SELECT 
     A.Id, A.Name, A.URL, 
     A.CostCentreId, C.CostCentre, 
     A.DepartmentId, D.DepartmentName, 
     A.ApplicationOwnerTypeId, AOT.Type, 
     A.SupportContact, 
     A.IsActive, A.AddedOn, A.AddedBy, A.ModifiedOn, A.ModifiedBy 
    FROM 
     dbo.Applications A 
     INNER JOIN dbo.Central_CostCentre_Main C ON A.CostCentreId = C.CostCentreId 
     LEFT OUTER JOIN dbo.Central_Department_Main D ON A.DepartmentId = D.DepartmentID 
     INNER JOIN dbo.ApplicationOwnerType AOT ON A.ApplicationOwnerTypeId = AOT.Id 
    WHERE  
     A.CostCentreId = @CostCentreId 
    AND CASE WHEN @DepartmentId IS NULL THEN 1 ELSE CASE WHEN A.DepartmentId = @DepartmentId THEN 1 ELSE 0 END END = 1 
    AND CASE WHEN @IsActive IS NULL THEN 1 ELSE CASE WHEN A.IsActive = @IsActive THEN 1 ELSE 0 END END = 1 
    ORDER BY [Name] 
END 

現在,在此過程中,如果我通過@ DepartmentID的= 24,然後我只得到了部24結果,但是我希望它顯示與@DepartmentId結果= 24和對於departmentsId = null

我應該如何修改過程來獲取此?

回答

4

試試這個作爲你的where子句:

WHERE  
    A.CostCentreId = @CostCentreId AND 
    (A.DepartmentId = @DepartmentId OR A.DepartmentId IS NULL 
     OR @DepartmentId IS NULL) /* also return row if the arg is null */ AND 
    A.IsActive = ISNULL(@IsActive, 1) 
ORDER BY [Name] 

編輯:您可能還可以嘗試:

WHERE  
    A.CostCentreId = @CostCentreId AND 
    (ISNULL(A.DepartmentId, @DepartmentId) = @DepartmentId 
     OR @DepartmentId IS NULL) /* also return row if the arg is null */ AND 
    A.IsActive = ISNULL(@IsActive, 1) 
ORDER BY [Name] 
+0

謝謝,這部分工作。如果'@DepartmentId'爲空,只提供'@CostCentreId',我得到零行。簡而言之,它只在提供'@DepartmentId'時才起作用。我想要它無論如何.. – user1181942 2012-03-05 07:21:22

+1

請看我編輯的答案。這應該照顧空參數。 – tobias86 2012-03-05 07:34:22

+0

謝謝...這是完美的.. – user1181942 2012-03-05 07:36:30

1
WHERE COALESCE(A.DepartmentId, 'x') = COALESCE(@DepartmentId, A.DepartmentId, 'x') 

假設'x'DepartmentId類型的有效價值,但不存在於域中。

但是,考慮使用一系列IF塊可能會獲得更好的性能。

相關問題