Skip to content
Advertisement

IF Exists then update in mysql

New to MySQL, need help in translating the next query to 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; 

Advertisement

Answer

Based on the comments posted on your question, here is a code snippet that should answer your need. It works by first checking if the column exists in INFORMATION_SCHEMA, and then dynamically building a SQL query that is prepared, then executed. It the column does not exists, a dummy query is executed instead of the UPDATE. I tested it in 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;
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement