0

I'm trying to build a query that takes some input parameters. Few things to note...

  1. Not all parameters are required to be passed to the query.
  2. If a parameter is not going to be passed to the query, must it still be passed anyway but as NULL?
  3. If a parameter is not passed, how would I build it to not include the parameter?

So say you have...

IN name VARCHAR(30),
IN age VARCHAR(2),
IN address VARCHAR(50)

And you only want to search by name...

SELECT * FROM Table WHERE 
(
NAME LIKE CONCAT(name, '%')
);

This doesn't seem to work because the age wasn't passed in. Or what if the name was passed in and the address but not the age? How would I build that?

John Woo
  • 258,903
  • 69
  • 498
  • 492
Shane LeBlanc
  • 2,633
  • 13
  • 42
  • 74

3 Answers3

1

The issue is optinal parameters Cannot be used in MYSQL.

The workaround is to pass null value for parameter and inside the stored procedure use IF statement to handle the different situations.

Take a look here:

Writing optional parameters within stored procedures in MySQL?

Community
  • 1
  • 1
S Nash
  • 2,363
  • 3
  • 34
  • 64
1

As a previous poster state, pass NULL for the unused parameters. Then structure your query similar to...

SELECT * FROM Table WHERE 
(
  ((nameParameter IS NULL) OR (NameColumn LIKE '%' + NameParameter + '%'))
  AND 
  ((ageParameter IS NULL) OR (AgeColumn = ageParameter))
  AND 
  ((addressParameter IS NULL) OR (AddressColumn = addressParameter))
)
dazedandconfused
  • 3,131
  • 1
  • 18
  • 29
0

Try this:

SELECT * FROM Table
WHERE name LIKE '%nametofind%';
Gimmy
  • 3,781
  • 2
  • 18
  • 27