I have this code:
ALTER TABLE `settings`
ADD COLUMN `multi_user` TINYINT(1) NOT NULL DEFAULT 1
And I want to alter this table only if this column doesn't exist.
I'm trying a lot of different ways, but nothing works:
ALTER TABLE `settings`
ADD COLUMN IF NOT EXISTS `multi_user` TINYINT(1) NOT NULL DEFAULT 1
With procedure:
DELIMITER $$
CREATE PROCEDURE Alter_Table()
BEGIN
DECLARE _count INT;
SET _count = ( SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'settings' AND
COLUMN_NAME = 'multi_user');
IF _count = 0 THEN
ALTER TABLE `settings` ADD COLUMN `multi_user` TINYINT(1) NOT NULL DEFAULT 1
END IF;
END $$
DELIMITER ;
I got error in END IF, then in END and then in 1
How can I make this as simple as possible?
Use
PREPARE
/EXECUTE
and querying the schema. The host doesn't need to have permission to create or run procedures :Use the following in a stored procedure:
hope this will help you
or
Here is a solution that does not involve querying
INFORMATION_SCHEMA
, it simply ignores the error if the column does exist.P.S. Feel free to give it other name rather than
?
I used this approach (Without using stored procedure):
SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'tbl_name' AND COLUMN_NAME = 'column_name'
If it didnt return any rows then the column doesn't exists then alter the table:
ALTER TABLE
tbl_name
ADD COLUMNcolumn_name
TINYINT(1) NOT NULL DEFAULT 1Hope this helps.
Add field if not exist:
addFieldIfNotExists code: