I am writing a stored procedure where I have an input parameter called my_size that is an INTEGER. I want to be able to use it in a LIMIT
clause in a SELECT
statement. Apparently this is not supported, is there a way to work around this?
# I want something like: SELECT * FROM some_table LIMIT my_size; # Instead of hardcoding a permanent limit: SELECT * FROM some_table LIMIT 100;
Mysql also supports the concept of User-defined variables, which allows passing of a value from one statement to another. A user-defined variable in Mysql is written as @var_name where, var_name is the name of the variable and can consist of alphanumeric characters, ., _, and $.
To get only the specified rows from the table, MySQL uses the LIMIT clause, whereas SQL uses the TOP clause, and Oracle uses the ROWNUM clause with the SELECT statement.
MySQL provides a LIMIT clause that is used to specify the number of records to return. The LIMIT clause makes it easy to code multi page results or pagination with SQL, and is very useful on large tables.
In MySQL the LIMIT clause is used with the SELECT statement to restrict the number of rows in the result set. The Limit Clause accepts one or two arguments which are offset and count. The value of both the parameters can be zero or positive integers.
For those, who cannot use MySQL 5.5.6+ and don't want to write a stored procedure, there is another variant. We can add where clause on a subselect with ROWNUM.
SET @limit = 10; SELECT * FROM ( SELECT instances.*, @rownum := @rownum + 1 AS rank FROM instances, (SELECT @rownum := 0) r ) d WHERE rank < @limit;
STORED PROCEDURE
DELIMITER $ create PROCEDURE get_users(page_from INT, page_size INT) begin SET @_page_from = page_from; SET @_page_size = page_size; PREPARE stmt FROM "select u.user_id, u.firstname, u.lastname from users u limit ?, ?;"; EXECUTE stmt USING @_page_from, @_page_size; DEALLOCATE PREPARE stmt; end$ DELIMITER ;
USAGE
call get_users(1, 10);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With