我有存储过程:
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的结果
我应该如何修改程序才能得到这个?
答案 0 :(得分: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]
答案 1 :(得分:1)
WHERE COALESCE(A.DepartmentId, 'x') = COALESCE(@DepartmentId, A.DepartmentId, 'x')
假设'x'
是类型DepartmentId
的有效值,但在域中不存在。
但是,请考虑使用一系列IF
块可以获得更好的性能。