Reputation: 2157
table orders
customers_id | name
1 | jimmy
I want to add a field 'refer_id' in table orders if it is not exists
customers_id | name | refer_id
1 | jimmy | 0
how to write if conditions?
alter table orders add refer_id int(11) default 0 if ...
Upvotes: 0
Views: 122
Reputation: 1602
Try this
delimiter '//'
CREATE PROCEDURE addcol() BEGIN
IF NOT EXISTS(
SELECT * FROM information_schema.COLUMNS
WHERE COLUMN_NAME='refer_id' AND TABLE_NAME='orders'
)
THEN
alter table orders add refer_id int(11) default 0
END IF;
END;
//
delimiter ';'
CALL addcol();
DROP PROCEDURE addcol;
Upvotes: 1
Reputation: 40318
It's not built it but it can be accomplished using the information_schema database
Upvotes: 0
Reputation: 37233
why using if here ?
try this
ALTER TABLE orders ADD refer_id int(11) default 0 AFTER name;
Upvotes: 1