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
Related
I have hundreds of databases with some structurally identical (but over time changing) tables. Data of a certain table (from all DBS) should be copied into one central table ('ex_objects') in a central database ('db_central'; there are no pk conflicts). I've used a trigger in each DB for this purpose. But since the table structure is changing almost on a daily basis, it's a pain to update the fields in the ON DUPLICATE KEY part of the trigger's query. And someone could forget to modify the trigger after modifying the table structure. So I came across a possible solution to build that particular part of the query dynamically. This actually works on a script (PHP) basis, but I don't get the trigger done. I don't see what I am missing here.
BEGIN
DECLARE VAL_FIELDS TEXT;
SET VAL_FIELDS = (SELECT GROUP_CONCAT( CONCAT(COLUMN_NAME,"=values(", COLUMN_NAME,")") SEPARATOR ", ") FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'db_central' AND TABLE_NAME = 'ex_objects');
-- SELECT GROUP_CONCAT( CONCAT(COLUMN_NAME,"=values(", COLUMN_NAME,")") SEPARATOR ", ") INTO VAL_FIELDS FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'db_central' AND TABLE_NAME = 'ex_objects';
-- SELECT #VAL_FIELDS := GROUP_CONCAT( CONCAT(COLUMN_NAME,"=values(", COLUMN_NAME,")") SEPARATOR ", ") INTO VAL_FIELDS FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'db_central' AND TABLE_NAME = 'ex_objects';
IF NEW.online = 1 THEN
INSERT INTO db_central.ex_objects
SELECT * FROM ex_objects WHERE id = NEW.id AND client_id = NEW.client_id AND NEW.online = 1
ON DUPLICATE KEY UPDATE VAL_FIELDS;
END IF;
END
I get the error that there's something wrong at ; END IF; END. Well, that means for me, that either the VAL_FIELDS variable after KEY UPDATE isn't recognized at all or the parser expects at least one equation (something like VAL_FIELDS = whatever). But in this case, it wouldn't solve my underlying problem at all.
The SELECT GROUP_CONCAT( CONCAT(COLUMN_NAME,"=v ... FROM INFORMATION_SCHEMA.C ... Query works well and results in something similar to id=values(id), xfield=values(xfield), yfield=values(yfield) (but with a few hundred fields, since the table is actually pretty huge).
The full error: SQL Error (1064): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ';
END IF;
END' at line 10
You must build the SQL using CONCAT, etc, then prepare and execute it. There is no 'interpolation'.
Since it is a TRIGGER, that won't work.
However, since a TRIGGER applies to a particular table, you may as well simply spell out the query, not construct it. You have most of what it takes to manually get the query generated for you (SELECT ... I_S ...). Add some more columns for OLD.col to fill out the thing; viola, you have the query that you need.
I've tried every possible combination I can think of to resolve this error but it keeps happening. Any help appreciated. This is just modifying the sakila sample database to do more complex things with.
See towards bottom I labeled the error with -- HERE!.
USE sakila;
DROP PROCEDURE IF EXISTS sp_randCustMult;
DELIMITER //
CREATE PROCEDURE sp_randCustMult()
BEGIN
/* section of code left out for troubleshooting
IF EXISTS (SELECT * FROM information_schema.columns WHERE table_name = customer AND column_name = multiplier)
THEN ALTER TABLE customer DROP COLUMN multiplier;
IF EXISTS (SELECT * FROM information_schema.columns WHERE table_name = customer AND column_name = cust_ranking)
THEN ALTER TABLE customer DROP COLUMN cust_ranking;
END IF;
*/
-- add new columns
ALTER TABLE customer
ADD COLUMN multiplier DECIMAL(3,2) AFTER active;
/* this column not relevant now
ALTER TABLE customer
ADD COLUMN cust_ranking VARCHAR(10) AFTER multiplier;
*/
-- declare a counter
SET #start = (SELECT MIN(customer_id) FROM customer);
SET #stop = (SELECT MAX(customer_id) FROM customer);
-- start while loop
WHILE #start <= #stop
DO
UPDATE customer
-- insert multiplier based on random distribution
SET multiplier =
(SELECT
(CASE
WHEN RAND() <= 0.65 THEN 1.00
WHEN RAND() <= 0.90 THEN 0.85
WHEN RAND() <= 1.00 THEN 1.05
END)
)
WHERE customer_id = #start;
-- tick counter one up
SET #start = #start + 1;
END WHILE;
-- HERE! syntax error on END before //
END//
DROP PROCEDURE sp_randCustMult//
DELIMITER ;
EDIT1: To clarify, MySql version is:
MySQL Workbench Community (GPL) for Mac OS X version 6.1.4 revision 11773 build 1454
And the error response from Workbench:
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 'END' at line 35
EDIT2: Edited code as suggested. Error no longer happens, however data is not being updated at all. (all NULL in new column)
Your CREATE PROCEDURE doesn't match the required syntax as described in the MySQL manual (simplified below by including just the relevant parts):
CREATE
PROCEDURE sp_name ([proc_parameter[,...]])
routine_body
routine_body:
Valid SQL routine statement
The routine_body consists of a valid SQL routine statement. This can be a simple statement such as SELECT or INSERT, or a compound statement written using BEGIN and END. Compound statements can contain declarations, loops, and other control structure statements. The syntax for these statements is described in Section 13.6, “MySQL Compound-Statement Syntax”.
Therefore, this junk…
IF EXISTS (SELECT * FROM information_schema.columns WHERE table_name = customer AND column_name = multiplier)
THEN ALTER TABLE customer DROP COLUMN multiplier;
IF EXISTS (SELECT * FROM information_schema.columns WHERE table_name = customer AND column_name = cust_ranking)
THEN ALTER TABLE customer DROP COLUMN cust_ranking;
END IF;
… is illegal. Perhaps you meant to move it into the BEGIN … END compound statement?
You also need a semicolon after END WHILE.
All functional logic must be between the tags BEGIN and END
So the IF conditions and alter query stuff must lie between BEGIN and END tags of procedure..
Thanks
I figured out the issues, here is the solution on CR:
https://codereview.stackexchange.com/questions/51603/mysql-modifying-sakila-database
I've been trying to write this simple mysql statement to check if a table exists:
IF object_id('carpool'.'users', 'U') is not null THEN
PRINT 'Present!'
ELSE
PRINT 'Not accounted for'
END IF
'carpool' is my schema and 'users' is a table
My sql version is 5.1.52-community
I keep getting this 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' at line 1 0.000 sec
I've tried several syntaxes such as IF BEGIN END ELSE BEGIN END to no avail.
any ideas?
It looks like you're trying to do a form of T-SQL, which MySQL does not support.
There is no print function, nor object_id. There is a form of IF function that can be used in a SELECT statement:
SELECT IF(1 = 1, 'present', 'not');
Are you reading MSSQL doco instead of MySQL doco? MSSQL supports these functions.
Depending on what you are after, you might want to use something like this:
SELECT
CASE WHEN EXISTS (SELECT NULL
FROM information_schema.tables
WHERE table_schema = 'carpool' AND table_name = 'users')
THEN 'Present'
ELSE 'Not accounted for' END;
This will check if table users exists in carpool schema. Please see example here.
Every statement must be terminated by semicolon.
Like this
IF object_id('carpool'.'users', 'U') is not null THEN
PRINT 'Present!';
ELSE
PRINT 'Not accounted for';
END IF;
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
MySQL: How to add a column if it doesn't already exist?
A tool I use is running this query but it's failing. I'm trying to help debug but cannot figure out what's wrong:
IF EXISTS( SELECT NULL FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'TOWNY_RESIDENTS'
AND table_schema = 'minecraft'
AND column_name != 'town-ranks')
THEN
ALTER TABLE TOWNY_RESIDENTS (ADD
`town-ranks` mediumtext,
`nation-ranks` mediumtext
);
The inner select query works fine. It seems the if exists syntax is wrong but I can't figure out how. Examples on website like SO show similar ideas...
The error is:
#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 WHERE table_name = 'TOW' at line 1
ALTER TABLE does not support IF EXISTS in MySQL. You can run your ALTER TABLE statement and ignore the resulting errors.
Another option is to do a SELECT INTO OUTFILE on information_schema to generate the ALTER TABLE statement if necessary, and then source that file to execute the ALTER TABLE statement.
I use MySQL 5.5.16.
I'm trying to check if a certain column exists in one of my tables. If it is I want to update its type & collation and if it isn't I want to add it to the table.
I've read similar posts Here and Here about IF EXISTS statement. But I'm getting an error with my query:
IF EXISTS (SELECT * FROM information_schema.columns WHERE table_name = 'e4s_account_details' AND column_name = 'accountID') THEN
ALTER TABLE 'e4s_account_details' CHANGE 'accountID' 'accountID' INT(10) NOT NULL AUTO_INCREMENT;
ELSE
ALTER TABLE 'e4s_account_details' ADD COLUMN 'accountID' INT(10) NOT NULL AUTO_INCREMENT;
END IF;
The error I get is:
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 * FROM information_schema.columns WHERE table_name = 'e4s_acco' at line 1
BTW, If I only query this:
(SELECT * FROM information_schema.columns WHERE table_name = 'e4s_account_details' AND column_name = 'accountID');
I get no error and the table+column information is returned.
You can't use this syntax directly with select query instead you can make stored procedure or query with information schema table for doing same.