Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bypassing the WHERE clause when the filter parameter comes as null

I have a procedure and need to bypass the WHERE clause where input as null.

Please find the below condition.

CREATE PROCEDURE [dbo].[spPERSON_SELECT]    
(
@PersonID INT = NULL,
@OrganizationID INT = NULL,
@ManagerID INT = NULL 
)
AS

BEGIN
SELECT PERSON.name, ORGANIZATION.name,PERSON.manager 
FROM PERSON 
    INNER JOIN ORGANIZATION 
        ON PERSON.person_id = ORGANIZATION.person_id    
WHERE PERSON.person_id = @PersonID  
    and ORGANIZATION.organization_id = @OrganizationID  
    and PERSON.manager_id = @ManagerID 

END
GO

Iam facing an issue while the input as null, at that case need to avoid where condition.

Example:

If @PersonID is null then my select query needs the following structure:

SELECT PERSON.name, ORGANIZATION.name,PERSON.manager 
FROM PERSON 
    INNER JOIN ORGANIZATION 
        ON PERSON.person_id = ORGANIZATION.person_id    
WHERE ORGANIZATION.organization_id = @OrganizationID
    and PERSON.manager_id = @ManagerID 

I would like to avoid dynamic queries.

like image 930
user2395176 Avatar asked Jan 19 '26 11:01

user2395176


1 Answers

Bracket each parameter and test for null i.e.

(PERSON.manager_id=@ManagerID or @ManagerID is NUll)
like image 189
RedEyedMonster Avatar answered Jan 22 '26 04:01

RedEyedMonster