0

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 ...  

3 Answers 3

1

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;
Sign up to request clarification or add additional context in comments.

1 Comment

1

why using if here ?

try this

   ALTER TABLE orders ADD refer_id int(11)  default 0  AFTER name;

Comments

0

It's not built it but it can be accomplished using the information_schema database

see here

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.