I have a function & I’m checking whether the table and column exist or not. If exits, then I need to alter the table.
delimiter $$
create function column_exists(ptable varchar(300), pcolumn varchar(100))
returns CHAR
reads sql data
begin
declare result CHAR(1);
select
if(count(1)>=1,'Y','N')
into
result
from
information_schema.columns
where
table_schema = 'schema' and
table_name = ptable and
column_name = pcolumn ;
return result;
end $$
but I’m getting an error while using the function:
SET @column_exists := column_exists('table_name', 'column_name');
IF @column_exists = 'Y' THEN
ALTER TABLE table_name MODIFY COLUMN column_name TIMESTAMP(3) DEFAULT '2019-01-01 00:00:00' NOT NULL;
ELSE
SELECT 'Column does not exist';
END IF;
Error:
SQL Error [1064] [42000]: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF @column_exists = 'Y' THEN
ALTER TABLE table_name MODIFY COLUMN column_na' at line 3
Error position: line: 2
Please guide to resolve the issue. Thanks.
2
Answers
MySQL does not directly support the use of the IF statement outside of a stored procedure, function, or query.
You have to include it in a stored procedure:
and call it like this:
I suggest use a Stored Procedure rather than a function.
Include your schema name in the input parameters. You might have the same table and column name on two different schemas.
Call it like the following
When successfully
When the column and table name doesn’t exist