Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

mysql - Why can't I use a variable as the table name in a stored procedure?

I'm trying to use a variable as the table name within a stored procedure and it's using it as a string literal instead of as the actual table name. Why is this? Is there another way I should be doing this (aside from just doing it in PHP)?

DROP PROCEDURE IF EXISTS settonull;

DELIMITER //

CREATE PROCEDURE settonull()
BEGIN
  DECLARE done INT DEFAULT FALSE;
  DECLARE _tablename VARCHAR(255);
  DECLARE _columnname VARCHAR(255);
  DECLARE cur1 CURSOR FOR SELECT CONCAT(TABLE_SCHEMA, '.', TABLE_NAME) AS table_name, COLUMN_NAME AS column_name FROM information_schema.COLUMNS WHERE IS_NULLABLE = 'YES' AND TABLE_SCHEMA = 'blip_notify' AND table_name = 'notify_queue' LIMIT 1;

  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

  OPEN cur1;

  read_loop: LOOP
    FETCH cur1 INTO _tablename, _columnname;

    IF done THEN
      LEAVE read_loop;
    END IF;

    UPDATE _tablename SET _columnname = NULL WHERE LENGTH(TRIM(_columnname)) = 0;

  END LOOP;

  CLOSE cur1;
END//

DELIMITER ;

CALL settonull();

Output:

0 row(s) affected, 1 warning(s)

Execution Time : 0 sec
Transfer Time  : 1.094 sec
Total Time     : 1.095 sec

Note Code : 1305
PROCEDURE settonull does not exist
---------------------------------------------------

0 row(s) affected

Execution Time : 0.002 sec
Transfer Time  : 1.011 sec
Total Time     : 1.014 sec
---------------------------------------------------

Query: call settonull()

Error Code: 1146
Table 'blip_notify._tablename' doesn't exist

Execution Time : 0 sec
Transfer Time  : 0 sec
Total Time     : 0.003 sec
---------------------------------------------------
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to use dynamic sql. ya, ugh.

SET @s = CONCAT('UPDATE ', _tablename, ' SET ', _columnname, ' = NULL WHERE LENGTH(TRIM(', _columnname, ')) = 0' );
PREPARE stmt FROM @s;
EXECUTE stmt;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...