Solved

Add Column To Mysql Table

Posted on 2009-07-13
2
365 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

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Foreword This is an old article.  Instead of using the MySQL extension that was used in the original code examples, please choose one of the currently supported database extensions instead.  More information is available here: MySQLi / PDO (http://…
Popularity Can Be Measured Sometimes we deal with questions of popularity, and we need a way to collect opinions from our clients.  This article shows a simple teaching example of how we might elect a favorite color by letting our clients vote for …
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

744 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now