如果存在则在mysql中更新

时间:2019-01-13 15:33:56

标签: mysql sql syntax

MySQL的新手,在将下一个查询转换为MySQL时需要帮助

If exists (select * from INFORMATION_SCHEMA.COLUMNS where table_name= 'MyTable' and column_name = 'MyColumn') 
    begin 
            update MyTable set MyColumn='' where Code=21 
    end; 

1 个答案:

答案 0 :(得分:1)

根据您对问题的评论,这是一个可以满足您需求的代码段。它的工作方式是先检查INFORMATION_SCHEMA中是否存在该列,然后动态构建已准备的SQL查询,然后执行。如果该列不存在,则执行伪查询而不是UPDATE。我在this db fiddlde中进行了测试。

SET @dbname = DATABASE();
SET @tablename = "my_table";
SET @columnname = "my_column";

-- check if the column exists
SELECT COUNT(*) INTO @cnt 
FROM INFORMATION_SCHEMA.COLUMNS
WHERE
    (table_name = @tablename)
    AND (table_schema = @dbname)
    AND (column_name = @columnname)
    ;

-- build a dynamic SQL statement
SET @preparedStatement = (SELECT IF(
  @cnt > 0,
  CONCAT("UPDATE ", @tablename, " SET ", @columnname, " = '' WHERE my_code = 21;"),
  "SELECT 1"
));

-- run the statement
PREPARE updateIfExists FROM @preparedStatement;
EXECUTE updateIfExists;
DEALLOCATE PREPARE updateIfExists;