MySQL准备语句中的多个查询(无过程)

时间:2016-03-24 16:21:27

标签: mysql if-statement prepared-statement

我有以下MySQL脚本,但它不起作用。当我从IF(INSERT INTO之后)删除第二个查询(SELECT)时,它开始工作。我的问题是:我可以在准备好的声明中执行多个查询但不能使用过程(最后一部分是我为此开设新问题的原因)?

提前致谢...

SQL:

SET @data1 = 'DATA_HERE' COLLATE utf8_general_ci
;

/* Random key */
SET @randomKey = CONCAT( 'rnd', DATE_FORMAT(NOW(), '%Y%m%d') , FLOOR( RAND() * 100 ) ) COLLATE utf8_general_ci
;

/* If not exists do an INSERT else SELECT a warning message */
SET @stmt = IF(
        ( SELECT EXISTS (
                SELECT
                    t0.id
                FROM
                    table t0
                WHERE 1
                    AND t0.key = @randomKey COLLATE utf8_general_ci
                    AND t0.data = @data1 COLLATE utf8_general_ci
            )
        ) = 0
        , CONCAT( "
            INSERT INTO
                table
            SET
                key = @randomKey COLLATE utf8_general_ci
                , data = @data1 COLLATE utf8_general_ci;

            SELECT
                t0.*
            FROM
                table t0
            WHERE 1
                AND t0.id = LAST_INSERT_ID(); " 
        )
        , CONCAT( "SELECT CONCAT( 'This random key already exists with this data!' );" )
    )
;

PREPARE stmt FROM @stmt
;
EXECUTE stmt
;

1 个答案:

答案 0 :(得分:0)

如果您的表格刚刚调用t0,那么您就不需要说table t0。只需使用SELECT * FROM t0 WHERE /* your predicate */

即可