我在执行存储过程时在dbo.Split
子句中使用函数WHERE
。当输入参数为NULL
时,我不想执行此函数。
E.g。
Create Procedure [dbo].[HRMS_RPT_CategoryWiseSeniorityList]
@fk_BranchRegion_ID bigint = null,
@pk_BranchType_ID nvarchar(100) = null
AS
BEGIN
Select distinct SR.fk_branchType_ID
from HRMS_Employee_ServiceRecord SR (nolock)
Inner Join HRMS_Mst_Branch B (nolock) On B.pk_Branch_ID = SR.fk_Branch_ID
Where
B.fk_BranchRegion_ID = IsNull(@fk_BranchRegion_ID,B.fk_BranchRegion_ID) --Region Condition
AND SR.fk_BranchType_ID in (SELECT * from dbo.Split( @pk_BranchType_ID,','))
END
当SR.fk_BranchType_ID
为@pk_BranchType_ID
时,我使用以下SQL忽略NULL
上的过滤器:
SR.fk_BranchType_ID = IsNull(@pk_BranchType_ID, SR.fk_BranchType_ID)
我想为@pk_BranchType_ID
做类似的事情。如果我像使用ISNULL
一样使用@pk_BranchType_ID
,则不会返回任何行。当它是NULL
。
当SR.fk_BranchType_ID
为@pk_BranchType_ID
时,如何让我的存储过程忽略NULL
上的过滤器?
答案 0 :(得分:0)
您可能希望将参数设置为null
,如下所示:
@fk_BranchRegion_ID bigint is Null,
@pk_BranchType_ID nvarchar(100) is Null
答案 1 :(得分:0)
如果要在输入参数为NULL时删除过滤器,可以在WHERE
子句中使用NULL检查,并与OR
结合使用,如下所示:
Create Procedure [dbo].[HRMS_RPT_CategoryWiseSeniorityList]
@fk_BranchRegion_ID bigint = null,
@pk_BranchType_ID nvarchar(100) = null
AS
BEGIN
Select
distinct SR.fk_branchType_ID
FROM HRMS_Employee_ServiceRecord SR WITH(nolock)
INNER JOIN HRMS_Mst_Branch B WITH(nolock)
ON B.pk_Branch_ID = SR.fk_Branch_ID
WHERE B.fk_BranchRegion_ID = IsNull(@fk_BranchRegion_ID,B.fk_BranchRegion_ID) --Region Condition
-- Remove filter on @pk_BranchType_ID when it is NULL
AND ( @pk_BranchType_ID IS NULL
OR SR.fk_BranchType_ID in (SELECT * from dbo.Split( @pk_BranchType_ID,',')) )
END