I have an application in which a user can pass in some or all of the parameters I’m requesting to the application. (Basically, he or she can stop providing input to various pieces of data whenever they choose.) Based on the input they are providing, I want to get back information from a MS SQL 2008 database with only the parameters that they gave me.
I’m picturing something like this, but I can’t seem to get it to work, and have no idea if it even can.
CREATE PROCEDURE [dbo].[SearchForSolution]
@Input1 int = 0,
@Input2 int = 0,
@Input3 int = 0,
AS
SELECT Name, SolutionValue
FROM MyTable
WHERE (IF @Input1 != 0) { BETWEEN LowValue AND HighValue }
AND (IF @Input2 != 0) { BETWEEN LowValue AND HighValue }
AND (IF @Input3 != 0) { < HighValue }
RETURN 0
Obviously, this isn’t working code, but it gives the general idea. I want to be able to use a variable as part of the WHERE clause, but only if it is not using the magic number (which, in this case, is 0).
I am not very familiar with the capabilities of SQL here and am not sure if what I want to do is possible. Everything I have tried so far has failed. If I am completely going down the wrong path here, I would appreciate a pointer in the correct direction.
Here is an approach…