Click here to Skip to main content
15,911,306 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to run a stored proc from a web application. I have multiple parameters with OR condition but i want the parameters which are left blank by the user to be ignored when the query execute.

What I have tried:

This is what i am trying

ALTER Proc [dbo].[spStatusReport]
@CUST_NAME varchar(20),
@CUST_CODE   varchar(10) = NULL 
as 
SELECT  CUST_CODE, DEPT_CODE,EMPLOYEE_CODE, EST_SCRAP, EXCH_RATE,
F_G_, LINE4, LOCATION
FROM Status_Report 
WHERE 
((@CUST_NAME IS NULL OR [LOCATION] LIKE '%' + @CUST_NAME + '%') OR
(@CUST_CODE IS NULL OR [CUST_CODE] LIKE '%' + @CUST_CODE + '%'))


But when i run
EXEC spStatusReport 'ABC',''


I get everything instead of only the ABC location
Posted
Updated 7-Dec-18 7:11am
v2

Take another look at your WHERE clause:
    (@CUST_NAME IS NULL OR [LOCATION] LIKE '%' + @CUST_NAME + '%')
OR
    (@CUST_CODE IS NULL OR [CUST_CODE] LIKE '%' + @CUST_CODE + '%')

You've used OR to combine the filters for both parameters. Therefore, if either parameter is NULL, then all records will be returned.

I suspect you mean to use And instead:
    (@CUST_NAME IS NULL OR [LOCATION] LIKE '%' + @CUST_NAME + '%')
AND
    (@CUST_CODE IS NULL OR [CUST_CODE] LIKE '%' + @CUST_CODE + '%')


You also need to appreciate the difference between NULL and an empty string. In your example, you're passing in an empty string, so @CUST_CODE IS NULL will be false. As a result, any rows where CUST_CODE is NULL will be excluded from your results, since they won't pass the LIKE '%%' test.

Therefore, I suspect you need:
    (@CUST_NAME IS NULL OR @CUST_NAME = '' OR [LOCATION] LIKE '%' + @CUST_NAME + '%')
AND
    (@CUST_CODE IS NULL OR @CUST_CODE = '' OR [CUST_CODE] LIKE '%' + @CUST_CODE + '%')
 
Share this answer
 
Observations:

0) Why bother specifying a default value of null if the code in the stored proc handles it?

2) Specifying an empty string for the 2nd parameter is NOT the same as specifying NULL.

Try changing it to the following:

EXEC spStatusRepport @CUST_NAME='ABC', @CUST_CODE=NULL
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900