I have put together a stored procedure which takes a single parameter and number of rows to be returned as parameters. This in essence does everything on the server so that there is no back and forth and will be slightly more efficient in the stored procedure. I have a white paper describing the procedure and the way to call it http://www.it-iss.com/mysql/mysql-st...-from-a-table/
Code:
DROP PROCEDURE IF EXISTS sp_random;
DELIMITER $$
CREATE PROCEDURE sp_random(IN pTableName VARCHAR(64), IN pLimit SMALLINT UNSIGNED)
NOT DETERMINISTIC
SQL SECURITY INVOKER
COMMENT 'A procedure that returns a random set of rows from a table'
BEGIN
DECLARE lCount INT UNSIGNED;
SET @uQuery := CONCAT('SELECT COUNT(1) INTO @uCount FROM ', pTableName);
PREPARE stmt FROM @uQuery;
EXECUTE stmt;
IF @uCount <= pLimit THEN
-- Return all values
SET @query := CONCAT('SELECT * FROM ', pTableName);
ELSE
-- Return limited number of entries
SET @offset := ROUND((@uCount - pLimit) * RAND(),0);
SET @query := CONCAT('SELECT * FROM ', pTableName, ' LIMIT ', @offset, ',', pLimit);
END IF;
PREPARE stmt FROM @query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END;
$$
DELIMITER ;
Bookmarks