简体   繁体   中英

MySQL variable used in where statement if variable set

I would like to set a query up to filter by some user variables, if I choose to set them.

SET @item_number = 12345;

SELECT * FROM table 

    IF(@item_number IS NOT NULL, item_number = @item_number, NULL)

but based on my errors, I am not doing this properly.

Is this in a proc? Or are you trying to build up some dynamic SQL.

If in a proc you can build up dynamic SQL and that might be easiest.

A method that is likely to be inefficient (due to trying to work out whether an index would help the query) but easy to understand would possibly be:-

SET @item_number = 12345;

SELECT * FROM table WHERE (@item_number IS NULL OR item_number = @item_number);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM