如果存在表,请执行某些操作

时间:2018-10-24 14:50:17

标签: mysql sql mariadb

我正在尝试查找是否存在名为OOK的表,如果有,请对其进行处理。这是我到目前为止的内容,不适用于有用的ERROR 1064 […] syntax error消息:

IF show tables like 'OOK' THEN
    DELETE FROM OOK WHERE Id = 'Development';
    INSERT INTO OOK VALUES ( 'Development', 'Localhost' );
END IF

这是为了支持某些旧代码,可能不是解决此问题的最佳方法。但是,它将根据我的需要进行修复。

由于我在回答中遇到很多语法错误,因此这里是确切的版本:Server version: 5.5.60-MariaDB MariaDB Server

2 个答案:

答案 0 :(得分:0)

您可以访问Information Schema,以检查表是否存在。另外,您将需要使用Dynamic SQL(以处理表名不存在的情况)

尝试以下操作:

IF EXISTS (SELECT 1
           FROM information_schema.tables 
           WHERE table_schema = 'your_database_name' 
           AND table_name = 'OOK') THEN 

  SET @s1 = 'DELETE FROM your_database_name.OOK WHERE Id = ?';
  SET @a = 'Development';
  PREPARE stmt1 FROM @s1;
  EXECUTE stmt1 USING @a;
  DEALLOCATE PREPARE stmt1;

  SET @s2 = 'INSERT INTO your_database_name.OOK VALUES (?, ?)';
  SET @b = 'Development';
  SET @c = 'Localhost';
  PREPARE stmt2 FROM @s2;
  EXECUTE stmt1 USING @b, @c;
  DEALLOCATE PREPARE stmt2;

END IF

答案 1 :(得分:0)

我在db的表复制过程中使用以下过程和函数:

用法

CALL do_something('mydb', 'OOK', 'Development', 'Development', 'Localhost');

实施

DELIMITER $$;
CREATE PROCEDURE do_something(
  IN dbName VARCHAR(255),
  IN tableName VARCHAR(255),
  IN id VARCHAR(255),
  IN value1 VARCHAR(255),
  IN value2 VARCHAR(255)
)
  BEGIN
    IF ( fn_table_exists(dbName, tableName) )
      THEN
        CALL statement(CONCAT(
          'DELETE FROM ', tableName, ' WHERE Id = "', id, '"'));
        CALL statement(CONCAT(
          'INSERT INTO ', tableName, ' VALUES ( "', value1, '", "', value2, '" )'));
      ELSE
        SELECT CONCAT(
          'ERROR: Table "', tableName, '" does not exist in the schema "', dbName, '".'
        ) AS ErrorMessage;
      END IF;
END$$
DELIMITER ;

DELIMITER $$;
CREATE PROCEDURE statement(IN dynamic_statement TEXT)
  BEGIN
      SET @dynamic_statement := dynamic_statement;
      PREPARE prepared_statement FROM @dynamic_statement;
      EXECUTE prepared_statement;
      DEALLOCATE PREPARE prepared_statement;
  END$$
DELIMITER ;

DELIMITER $$;
CREATE FUNCTION fn_table_exists(dbName VARCHAR(255), tableName VARCHAR(255))
  RETURNS TINYINT(1)
  BEGIN
    DECLARE totalTablesCount INT DEFAULT (
      SELECT COUNT(*)
      FROM information_schema.TABLES
      WHERE (TABLE_SCHEMA COLLATE utf8_general_ci = dbName COLLATE utf8_general_ci)
        AND (TABLE_NAME COLLATE utf8_general_ci = tableName COLLATE utf8_general_ci)
    );
    RETURN IF(
      totalTablesCount > 0,
      TRUE,
      FALSE
    );
END$$
DELIMITER ;