日期:2014-05-16 浏览次数:20987 次
PREPARE stmt_name FROM preparable_stmt; EXECUTE stmt_name [USING @var_name [, @var_name] ...]; {DEALLOCATE | DROP} PREPARE stmt_name;
mysql> PREPARE stmt1 FROM 'SELECT SQRT(POW(?,2) + POW(?,2)) AS hypotenuse'; mysql> SET @a = 3; mysql> SET @b = 4; mysql> EXECUTE stmt1 USING @a, @b; +------------+ | hypotenuse | +------------+ | 5 | +------------+ mysql> DEALLOCATE PREPARE stmt1; mysql> SET @s = 'SELECT SQRT(POW(?,2) + POW(?,2)) AS hypotenuse'; mysql> PREPARE stmt2 FROM @s; mysql> SET @a = 6; mysql> SET @b = 8; mysql> EXECUTE stmt2 USING @a, @b; +------------+ | hypotenuse | +------------+ | 10 | +------------+ mysql> DEALLOCATE PREPARE stmt2;
mysql> SET @a=1;mysql> PREPARE STMT FROM "SELECT * FROM tbl LIMIT ?"; mysql> EXECUTE STMT USING @a; mysql> SET @skip=1; SET @numrows=5; mysql> PREPARE STMT FROM "SELECT * FROM tbl LIMIT ?, ?"; mysql> EXECUTE STMT USING @skip, @numrows;
CREATE PROCEDURE `p1`(IN id INT UNSIGNED,IN name VARCHAR(11)) BEGIN lable_exit: BEGIN SET @SqlCmd = 'SELECT * FROM tA '; IF id IS NOT NULL THEN SET @SqlCmd = CONCAT(@SqlCmd , 'WHERE id=?'); PREPARE stmt FROM @SqlCmd; SET @a = id; EXECUTE stmt USING @a; LEAVE lable_exit; END IF; IF name IS NOT NULL THEN SET @SqlCmd = CONCAT(@SqlCmd , 'WHERE name LIKE ?'); PREPARE stmt FROM @SqlCmd; SET @a = CONCAT(name, '%'); EXECUTE stmt USING @a; LEAVE lable_exit; END IF; END lable_exit; END; CALL `p1`(1,NULL); CALL `p1`(NULL,'QQ'); DROP PROCEDURE `p1`;