MySQL idempotent version of add column failing - mysql

MySQL here. Trying to add a column to a table in idempotent fashion. In reality it will be a SQL script that gets ran as part of an application data migration, so it will be ran over and over and I want to make sure that we only run it if the column does not already exist.
My best attempt so far:
IF NOT EXISTS (SELECT 1
FROM information_schema.COLUMNS
WHERE
TABLE_SCHEMA = 'myapp'
AND TABLE_NAME = 'mytable'
AND COLUMN_NAME = 'fizzbuzz')
BEGIN
alter table myapp.mytable
add column fizzbuzz tinyint(1) not null default false;
END
yields a vague syntax error:
"IF" is not valid at this position, expecting EOF, ALTER, ANALYZE, BEGIN, BINLOG, CACHE, ...
Can anyone spot where my syntax is going awry?

use:
ALTER TABLE myapp.mytable
ADD COLUMN IF NOT exists fizzbuzz TINYINT(1) NOT NULL DEFAULT FALSE;

Related

How do I use an IF statement with an ALTER statement in MySQL?

I'm looking to add a column only if it does not already exist before. The motivation for this is that we can upgrade any version of a production instance to the latest version.
This is what I'm trying, but I keep getting a syntax error near the IF statement:
use database_name
SELECT #rowcount:=COUNT(column_name)
FROM information_schema.columns
WHERE table_name = 'table_name'
AND column_name = 'column_2';
IF #rowcount < 1 THEN
ALTER TABLE table_name
ADD COLUMN column_2 VARCHAR(42) DEFAULT 'abcd',
END IF;
commit;
What am I doing wrong?
You asked:
How do I use an IF statement with an ALTER statement in MySQL?
You Can't Do Thatâ„¢. MySQL's DML and DDL aren't as well integrated as other makes and models of table server.
You can't put DML inside stuff like IF statements or transactions. If you need to do that sort of operation you'll have to use an application programming language to issue simpler SQL.
I think you should change
IF #rowcount < 0 THEN
ALTER TABLE table_name
ADD COLUMN column_2 VARCHAR(42) DEFAULT 'abcd',
END IF;
and check if table exist.
As #Ollie Jones mentions and from looking at Using an IF Statement in a MySQL SELECT query, it looks like it's not possible to use if statements outside of sprocs or functions.
I followed the steps on http://www.cryer.co.uk/brian/mysql/howto_add_column_unless_exists.htm:
Create the sproc (see link)
Call the sproc when wanting to add a new column to a table
Alternatively, as #Ollie Jones mentions, you can do it at an application level, but I'm using .sql files in my case. It also saves on making multiple calls to the DB vs. having it done at the server level.

create table if not exists, insert columns if missing, best way

I need to create a table if it doesnt exist, and add missing columns in the proper order if the table already exists.
I know how to do it with lots of queries, and if statements and so on, but what I am asking here is what the best solution would be.. Maybe there is a special query to do this, or a smart way.
I would do it this way:
create table if not exists (all columns as they should be)
compare all the columns (if some are missing they will be added, else not)
Is this the best way or are there better ways to do it?
ADDITIONAL INFO
the colums need to be added at the right position. I have a list of strings representing all the columns in the proper order. using vb.net I am iterating through these strings.
Check out this for instance. It's basically about querying the data dictionary and adding columns only if they do not exist:
IF NOT EXISTS(SELECT NULL
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'tablename'
AND table_schema = 'db_name'
AND column_name = 'columnname') THEN
ALTER TABLE `TableName` ADD `ColumnName` int(1) NOT NULL default '0';
END IF;
Putting it in a procedure makes it quite handy.
p.s. note about column positions: from the docs
To add a column at a specific position within a table row, use FIRST
or AFTER col_name. The default is to add the column last. You can also
use FIRST and AFTER in CHANGE or MODIFY operations to reorder columns
within a table.
You can use following codes for that:
if not exists(select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'table_name' and COLUMN_NAME = 'column_name')
BEGIN
ALTER TABLE table_name ADD
ToUser uniqueidentifier NULL
END

Using variable as integer for AUTO_INCREMENT

I'm rather new to fiddling around in SQL and MySQL, although I stumbled upon this problem. I'm trying to get a number of how many rows are there in one table and set this number onto anothers AUTO_INCREMENT value. The problem is, MySQL workbench triggers a syntax error when I try to assign value via a variable. I tried to convert the query to unsigned integer, although not sure if it did work. Query for row amount returns the required number. What am I doing wrong?
SET #size = CONVERT((SELECT TABLE_ROWS FROM information_schema.tables WHERE table_name='Persons' and table_schema = 'Movies2'), unsigned);
ALTER TABLE Movies2.Actors AUTO_INCREMENT=#size;
The following should work:
ALTER TABLE Movies2.Actors AUTO_INCREMENT = (SELECT COUNT(*) FROM Movies2.Persons);

To avoid typos how can I make MySql sql compiler check for table definitions when creating a new procedure?

Having the following DDL in MySql 5.5.x.
create table if not exists t1 (col1 int);
and
CREATE PROCEDURE my_proc()
BEGIN
select inexistent_column from t1;
END;
Why the procedure is created without errors?
I expect it to throw that inexistent_column is not known or does not exists.
How can I make MySql sql compiler check for table definitions?
UPDATE: Rephrase
I just want a way to avoid a typo in a column while developing, meaning, creating a brand new procedure. Is there any way to do this? Maybe that should've been the question to ask from the start.
The server will only do syntax checking, but you can check for the existence of columns yourself. All existing tables and columns are defined in the information_schema.
You could use a query like this to check if your column exists:
SELECT *
FROM information_schema.COLUMNS
WHERE
TABLE_SCHEMA = 'your_database_name'
AND TABLE_NAME = 'your_table_name'
AND COLUMN_NAME = 'some_column'

Add column if not exist

How could I want to add a column if not exist.
I tried this code:
IF EXISTS( SELECT NULL
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'forwind.measuringdata_fino_10_00000000'
AND table_schema = 'forwind'
AND column_name != 'F1_USA(40)_u') THEN
ALTER TABLE `forwind.measuringdata_fino_10_00000000` ADD `F1_USA(40)_u` FLOAT NOT NULL default '0';
END IF;
but I get the following error:
Error Code: 1064 You have an error in
your SQL syntax; check the manual that
corresponds to your MySQL server
version for the right syntax to use
near 'IF EXISTS( SELECT NULL
FROM INFORMATION_SCHEMA.COLUMNS
Good for me if somebody know an other solution!
MySQL does not support anonymous IF statements like that.
You have at least 3 options to address this:
1) Just run the ALTER TABLE statement and ignore the Duplicate column name error if the column already exists. If you're executing a bunch of DDL in a script you can use mysql -f to ignore the errors and keep going.
2) Use a scripting language such as bash, python, perl etc to check for the existence of the column and then add it if it does not already exist.
3) Create a stored procedure in MySQL to check for the existence of the column and then add it if it does not already exist.
P.S. As an aside, I recommend against putting parentheses in column names, because that forces you to quote the column name every time you reference it.
------Add an IpAddress column in ActionsTracking table if -----
DECLARE #tableName varchar(MAX) ='ActionsTracking'
DECLARE #columnName varchar(MAX) ='IpAddress'
IF EXISTS(SELECT 1 FROM sys.columns
WHERE Name = #columnName
AND Object_ID = Object_ID(#tableName))
PRINT 'Column Already Exists'
ELSE
BEGIN
EXEC('ALTER TABLE '+#tableName+'
ADD '+ #columnName +' varchar(15) null')
PRINT 'Column Added Sucessfully'
END