Link to home
Start Free TrialLog in
Avatar of fjkilken
fjkilken

asked on

How to ignore a SQL parameter if it is to be left blank

I have a SQL Stored Proc and I have various parameters I pass into it, including one named @StockNbr.

I have a WHERE condition in the Stored Proc as follows:

WHERE LEFT(stk_nbr,1) IN (SELECT item Common.StrToTable(@StockNbr,100))

How do I modify the Stored Proc to ignore the @StockNbr parameter if I do not wany to pass-in a value for it?

Thanks
Fergal
ASKER CERTIFIED SOLUTION
Avatar of ProjectChampion
ProjectChampion
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
You can pass the value as NULL. Or default the value to NULL while creating the procedure.

Use the below code.

WHERE
   1 = (CASE
           WHEN @StockNbr IS NULL
              THEN 1
           ELSE 2
        END)
  OR LEFT(stk_nbr,1) IN (SELECT item Common.StrToTable(@StockNbr,100))

Open in new window


If you pass a valid value for @StockNbr, then it will use it. else it will ignore the where and fetch all the data from the Table.
Avatar of Vikas Garg
Hi,

You can modify the SP by providing default value to the Parameter in the stored procedure where the Parameter has bee mentioned in the SP.
for example
ALTER PROCEDURE [abc]
      
      @StockNbr varcahr(30) = '1,2'

By doing this you can Execute the SP Without passing the parameter but since the SP contains Where clause the Value in the Parameter set default will affect the result.
And if the where clause is not required you can also comment that portion
The solution that I gave will not have redundant code. Isn't a good one?
Avatar of fjkilken
fjkilken

ASKER

I'm afraid the solution provided by Project Champion was the first and most intuitive one for me to use, thus the reason why I accepted it.
That's fine. You are the asker :)