Solved

Add Column To Mysql Table

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

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Using in clause in query with many values 7 54
join tables 4 56
Slow MySQL (InnoDB) Query with Inner Join & GroupBy 7 55
How to fix Datetime in MySQL? 4 49
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…
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.

837 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