Tuesday, 15 May 2012
Optional Parameters MySQL
Today I was dealing with a problem I had come across many times before but I've decided to ignore! The problem is where you've got multiple parameters which form the basis of an MySql WHERE, however all these filters are optional. So I am normally left with the ugly task of building a WHERE clause by dynamically appending only those columns I need to filter at the same time checking if an AND or a WHERE prefix is needed! yuk!!!
Today I decided to take the bull by the horns and search for a better solution and after a lot of to-ing and fro-ing between forums and blogs I discovered the following syntax:
SELECT * FROM table
WHERE ((@field1 is null) OR (field1 = @field1))
AND ((@field2 is null) OR (field2 = @field2))
AND ((@field3 is null) OR (field3 = @field3))
Thus, now I am able to pre-write the entire query with all parameters but only filter by parameters which contain values... if a parameter is null it simply gets ignored!
Another hack bites the dust!!!
Labels:
mysql,
parameters
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment