I am having some problems here, I have actually had the same issue for a while now but I hack around and get it working in the end however I would like to know if I have missed a simple way of开发者_StackOverflow doing it.
Say if I have:
Field input 1
Field input 2
Field input 3 (empty)
Field input 4
I want to query SELECT * FROM tbl_table WHERE field1 LIKE ? AND field2 LIKE ? AND field3 LIKE ? AND field4 LIKE ?
Basically I come into trouble when an input is empty because its searching in a field and looking for null or another string when I want it to just discard the LIKE operator of the empty Input.
I know this might read really bad however its hard to get a point across some times.
SELECT * FROM tbl_table WHERE (field1 IS NULL OR field1 LIKE ?) AND (field2 IS NULL OR field2 LIKE ?) AND ....
Essentially, you need to check the value of the variable in the where clause. Check if it is null or has value like this.
Declare @input1 varchar(50);
Declare @input2 varchar(50);
Declare @input3 varchar(50);
Declare @input4 varchar(50);
SET @input1 = 'a'
SET @input2 = 'b'
SET @input3 = NULL
SET @input4 = 'c'
SELECT
*
FROM tbl_table
WHERE
(@input1 is null OR field1 LIKE @input1)
AND (@input2 is null OR field1 LIKE @input2)
AND (@input3 is null OR field1 LIKE @input3)
AND (@input4 is null OR field1 LIKE @input4)
精彩评论