为什么我的存储过程不使用我正在传递的参数mysql数据库

m1m5dgzv  于 2021-06-24  发布在  Mysql
关注(0)|答案(2)|浏览(340)

我试图创建一个存储过程,用递增的升序数字更新表中的一列。
我的密码

CREATE DEFINER=`cis23383518`@`192.168.122.1` PROCEDURE `Increment_rows`(IN TheTable VARCHAR(20),IN TheID VARCHAR(20))
BEGIN
DECLARE i INT;
SET i = 0;
UPDATE TheTable 
SET TheID = i,i= i+1;
END

我把这个程序称为

CALL Increment_rows('Officer','IncidentID');

我得到以下错误:表cis23383518.thetable不存在。

0sgqnhkj

0sgqnhkj1#

mysql不会用提供的参数替换表名,更新会查找名为thetable的表。如果要为过程提供表名,则必须构建sql语句并提交,例如

DROP PROCEDURE IF EXISTS `Increment_rows`;
DELIMITER $$

CREATE  PROCEDURE `Increment_rows`(IN TheTable VARCHAR(20),IN TheID VARCHAR(20))
BEGIN

set @sqlstmt =  concat('UPDATE ', THETABLE, ' SET STATUS =  (SELECT @I:=@I + 1 FROM (SELECT @I:=0) I) ORDER BY ID DESC;');
SELECT @SQLSTMT;
prepare stmt from @sqlstmt;
execute stmt;
deallocate prepare stmt;

END $$

注意使用变量来增加status列。如此给定

+----+----------+--------+
| id | username | status |
+----+----------+--------+
|  1 | John     |      0 |
|  2 | Jane     |      0 |
|  3 | Ali      |      0 |
|  6 | Bruce    |      0 |
|  7 | Martha   |      0 |
|  8 | Sidney   |      0 |
| 10 | charlie  |      0 |
| 12 | Elisa    |      0 |
| 14 | Samantha |      0 |
| 15 | Hannah   |      0 |
| 16 | Hannah   |      0 |
| 17 | Kevin    |      0 |
| 18 | Kevin    |      0 |
| 19 | Ruth     |      0 |
+----+----------+--------+
14 rows in set (0.00 sec)

MariaDB [sandbox]> CALL Increment_rows('USERS','INCIDENTID');
+----------------------------------------------------------------------------------------+
| @SQLSTMT                                                                               |
+----------------------------------------------------------------------------------------+
| UPDATE USERS SET STATUS =  (SELECT @I:=@I + 1 FROM (SELECT @I:=0) I) ORDER BY ID DESC; |
+----------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.01 sec)

MariaDB [sandbox]> select id,username,status from users;
+----+----------+--------+
| id | username | status |
+----+----------+--------+
|  1 | John     |     14 |
|  2 | Jane     |     13 |
|  3 | Ali      |     12 |
|  6 | Bruce    |     11 |
|  7 | Martha   |     10 |
|  8 | Sidney   |      9 |
| 10 | charlie  |      8 |
| 12 | Elisa    |      7 |
| 14 | Samantha |      6 |
| 15 | Hannah   |      5 |
| 16 | Hannah   |      4 |
| 17 | Kevin    |      3 |
| 18 | Kevin    |      2 |
| 19 | Ruth     |      1 |
+----+----------+--------+
14 rows in set (0.02 sec)

注意,我认为update语句可能需要where语句。

wh6knrhe

wh6knrhe2#

精简程序不是强制性的。
如果使用创建过程的相同用户标识调用该过程,只需删除它:

CREATE PROCEDURE `Increment_rows`(IN TheTable VARCHAR(20),IN TheID VARCHAR(20))
BEGIN
DECLARE i INT;
SET i = 0;
UPDATE TheTable 
SET TheID = i,i= i+1;
END

相关问题