Solved

Add Column To Mysql Table

Posted on 2009-07-13
2
369 Views
Last Modified: 2012-05-07
Hi to all,
I want to check field if not exists so add a field to table.
But i want to it just PURE SQL... with not php or etc...
is there any way?
/*
i want to add myfield  if it's not exists. just PURE SQL pls..
*/
ALTER TABLE mytable
ADD myfield varchar(20)

Open in new window

0
Comment
Question by:erenpasa
2 Comments
 
LVL 33

Expert Comment

by:snoyes_jw
ID: 24841033
Just add it anyway. If the field exists, it will return an error. If it doesn't exist, it will add it. If this is part of some longer script, run it with mysql --force < file.sql
0
 

Accepted Solution

by:
erenpasa earned 0 total points
ID: 24841179
DELIMITER $$
DROP PROCEDURE IF EXISTS AddColumn$$
CREATE PROCEDURE AddColumn(
      IN dbName TINYTEXT,
      IN tableName TINYTEXT,
      IN fieldName TINYTEXT,
      IN fieldDef TEXT)
BEGIN
      IF NOT EXISTS (
            SELECT * FROM information_schema.COLUMNS
            WHERE column_name=fieldName
            AND table_name=tableName
            AND table_schema=dbName
            )
      THEN
            SET @ddl=CONCAT('ALTER TABLE ',dbName,'.',tableName,
                  ' ADD COLUMN ',fieldName,' ',fieldDef);
            PREPARE stmt FROM @ddl;
            EXECUTE stmt;
      END IF;
END$$
0

Featured Post

U.S. Department of Agriculture and Acronis Access

With the new era of mobile computing, smartphones and tablets, wireless communications and cloud services, the USDA sought to take advantage of a mobilized workforce and the blurring lines between personal and corporate computing resources.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Foreword In the years since this article was written, numerous hacking attacks have targeted password-protected web sites.  The storage of client passwords has become a subject of much discussion, some of it useful and some of it misguided.  Of cou…
This guide whil teach how to setup live replication (database mirroring) on 2 servers for backup or other purposes. In our example situation we have this network schema (see atachment). We need to replicate EVERY executed SQL query on server 1 to…
Two types of users will appreciate AOMEI Backupper Pro: 1 - Those with PCIe drives (and haven't found cloning software that works on them). 2 - Those who want a fast clone of their boot drive (no re-boots needed) and it can clone your drive wh…
This video shows how to quickly and easily add an email signature for all users on Exchange 2016. The resulting signature is applied on a server level by Exchange Online. The email signature template has been downloaded from: www.mail-signatures…

776 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question