MYSQL How to alter table if column doesnt exist - mysql

I am using SQL which doesnt support INFORMATION_SCHEMA.COLUMNS. My code, which doesnt work
ALTER TABLE Report ADD IF NOT EXISTS LastName CHAR(25);
this works
ALTER TABLE Report ADD LastName CHAR(25);
which part is wrong?
IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Report' AND COLUMN_NAME = 'LastName' )
ALTER TABLE 'Report' ADD 'LastName' CHAR(25);

You need to quote the object names in the statement.
IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Report' AND COLUMN_NAME = 'LastName' )
ALTER TABLE MLReport ADD LastName CHAR(25);

Related

Is posible on insert query use auto-increment to concatenate with string for column value?

Is posible on insert query use auto-increment to concatenate with string for one column value?
The current AUTO-INCREMENT is = 89 name columns pkey
Example query string:
INSERT INTO `Tbl` (`ProcessCod`, `ProcessName`, ) VALUES(CONCAT('f-pdf-',AUTO-INCREMENT), 'Text-Description');
All in one query???
update i think on a string like this:
INSERT INTO `Tbl` (
`ProcessCod`,
`ProcessName`)
VALUES(
SELECT CONCAT('f-pdf-',`AUTO_INCREMENT`)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'INFO'
AND TABLE_NAME = 'Tbl',
'Text-Description'
);
the scope of my question is around the use of auto-increment (no primary key) to fill a column with it and concatenating with a dinamic string not a static prefix.
i have solved with this code:
INSERT INTO Tbl (
ProcessCod,
ProcessName
)VALUES(
(SELECT CONCAT('f-pdf-',`AUTO_INCREMENT`)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'INFO'
AND TABLE_NAME = 'Tbl'),
'Text-Description'
);
it was necessary to place the Select in parentheses so that it works correctly.

ALTER TABLE ADD COLUMN and automatic COLUMNS list

I am looking to add a new column to table using the suggestions provided here and here
In essence, I would like the (fields_in_orig_table) to be populated automatically, and not having to enter them manually (have many columns and this changes from table to table):
CREATE TABLE games_new LIKE games_orig;
ALTER TABLE games_new ADD COLUMN location varchar(256);
INSERT INTO games_new (fields_in_orig_table) SELECT * FROM games_orig;
RENAME TABLE games_orig TO games_old, games_new TO games_orig;
DROP TABLE games_old;
My thought goes around this:
CREATE TABLE games_new LIKE games_orig;
ALTER TABLE games_new ADD COLUMN version varchar(256);
INSERT INTO games_new
(SELECT CONCAT(GROUP_CONCAT(column_name ORDER BY ordinal_position
SEPARATOR " , "), " ") AS columns
FROM information_schema.columns
WHERE table_schema = 'games' AND table_name = 'games_orig' )
SELECT * FROM games_orig;
RENAME TABLE games_orig TO games_old, games_new TO games_orig;
DROP TABLE games_old;
This gives me syntax error (near the Select concat....).
The original syntax to get comma delimited column listings is:
SELECT CONCAT("'", GROUP_CONCAT(column_name ORDER BY ordinal_position SEPARATOR "', '"), "'") AS columns
FROM information_schema.columns
WHERE table_schema = 'db_name' AND table_name = 'tbl_name'
In my query, I have removed the extra quotes, as I figure my query does not require quotes as part of the column listing.
What am I doing wrong here? Who could help, please?
INSERT INTO games_new
VALUES (SELECT CONCAT....
When inserting values in the table use INSERT INTO tablename VALUES (fields) instead of INSERT INTO tablename SET(fields).
CREATE TABLE games_new LIKE games_orig;
ALTER TABLE games_new ADD COLUMN version varchar(256);
INSERT INTO games_new
VALUES
(SELECT CONCAT(GROUP_CONCAT(column_name ORDER BY ordinal_position
SEPARATOR ' , '), ' ') AS columns
FROM information_schema.columns
WHERE table_schema = 'games' AND table_name = 'games_orig' )
SELECT * FROM games_orig;
RENAME TABLE games_orig TO games_old, games_new TO games_orig;
DROP TABLE games_old;
You haven't specified which column you want to insert into, because your nested query is returning only 1 value
INSERT INTO games_new (column_name_u_want_to_insert_value_into)
SELECT cast(concat(group_concat(column_name ORDER BY ordinal_position SEPARATOR " , "), " ") AS CHAR) AS columns
FROM information_schema.columns
WHERE table_name = 'games_orig';
also, if you are running all the statements together, add semicolon(;) for the insert query as well

Mysql How to only select from a column if the column exists

I need to be able to check if a column exists and if it does then I want to SELECT from it.
I am trying lots of different variations but I'm not even sure if this is possible.
Here's my latest attempt:
SELECT
IF (EXISTS (SELECT `Period` AS `Period` FROM myview), `PERIOD`,
IF (EXISTS (SELECT `Country` AS `COUNTRY` FROM myview),`COUNTRY` FROM myview ;
Any ideas?
EDIT
I had seen the other question on here: MySQL, Check if a column exists in a table with SQL
But I still struggle with the if statement. I can check to see if the column exists using the answer in the question above. But my question is - how to execute a select statement from that column if the result is found to be true.
EDIT 2
The answer below indicates that I should use the BEGIN and END statement and this makes sense. However, my query complains at the first line. It says 'unexpected IF' - can anybody confirm if this is the right syntax fro MYSQL?
if( exists (SELECT *
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = 'db_name'
AND TABLE_NAME = 'view_name'
AND COLUMN_NAME = 'column_name') )
begin
SELECT `column_name` FROM `view_name`
end
Thanks in advance.
This query will give you whether a column exists.
SELECT *
FROM information_schema.COLUMNS
WHERE
TABLE_SCHEMA = 'db_name'
AND TABLE_NAME = 'table_name'
AND COLUMN_NAME = 'column_name'
If you want to check if some columns exist then perform a select statement you need to first check your columns exist. Then perform the select:
if (exists (SELECT * FROM information_schema.COLUMNS WHERE TABLE_NAME = 'myview' AND COLUMN_NAME = 'Period') and exists (SELECT * FROM information_schema.COLUMNS WHERE TABLE_NAME = 'myview' AND COLUMN_NAME = 'Country'))
begin
select `Period`, `Country` from myview
end
If the IF condition is true, then you will execute anything inside the BEGIN and END.
I came across the same situation where I had some product tables created by sheets uploaded by users. Sometimes, the sheets did not have column named "obsolete", so I had to import all products from the sheet but not the obsolete ones.
I am not modifying my query based on the original question that was asked, but here is my solution:
SELECT
t2.model,
(
SELECT
COUNT(*) AS _count
FROM db.table t1
WHERE
`obsolete`=1
AND t1.model=t2.model
) AS `obsolete`
FROM (
SELECT
0 AS `obsolete`,
t3.model
FROM db.table t3
) t2
There are 2 most important parts in this query:
We are selecting 0 AS obsolete as dummy to fool MySql which will be used even if column does not exist when selecting COUNT(*).
We have named tables as t1 & t2 to match the column model as t1.model=t2.model.

Add a column if it doesn't exist in mysql, need a little help debugging

I have the following query that I want to use to check whether if a column exists and then insert it if it doesn't.
$new_field ="IF NOT EXISTS
(SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE
TABLE_SCHEMA = 'dashboard'
AND TABLE_NAME = '".$this->table_name."'
AND COLUMN_NAME = 'timestamp')
BEGIN
ALTER TABLE `".$this->table_name."`
ADD mytimestamp DATETIME NOT NULL AFTER day_chan3";
I am not sure where my mistake is as I am not that good at sql queries and I would really aprpeciate the help. I know this looks very n00b and i am one.
I made the changes mentioned in the comment and I echoed the output of my query,
IF NOT EXISTS
(SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'dashboard'
AND TABLE_NAME = 'admin_tmp' AND COLUMN_NAME = 'timestamp')
BEGIN ALTER TABLE `admin_tmp` ADD mytimestamp DATETIME NOT NULL AFTER day_chan3
Your if statement is mixing up backticks with single quotes. Use backticks only when necessary and only for identifiers (column names and table names). Use single quotes only for string and date constant values. So, try this:
(SELECT *
FROM information_schema.COLUMNS
WHERE
TABLE_SCHEMA = 'dashboard'
-----------------------------^ --------^
AND TABLE_NAME = '".$this->table_name."'
---------------------------^ --------------------^
AND COLUMN_NAME = 'timestamp')
----------------------------^ --------^

MySQL modify all field lengths

Is there any way you can update the length of all fields in MySQL? I tried:
ALTER TABLE mytable MODIFY * VARCHAR(150);
But no joy. Any suggestions?
You can use info from information_schema database to generate query for you.
If you need to change all varchar(100) columns to varchar(150) in your table myTable use query:
SELECT CONCAT( 'ALTER TABLE `myTable`',
GROUP_CONCAT(
CONCAT( '\nMODIFY ', COLUMN_NAME, ' VARCHAR(150) ' ),
'' )
) AS query
FROM information_schema.COLUMNS
WHERE DATA_TYPE = 'varchar'
AND CHARACTER_MAXIMUM_LENGTH = 100
AND TABLE_SCHEMA = 'myDatabase'
GROUP BY TABLE_NAME
and then copy/paste output as another query to do the actual job.
You have to modify each column specifically.
ALTER TABLE mytable
MODIFY col_1 VARCHAR(150),
MODIFY col_2 VARCHAR(150),
MODIFY col_3 VARCHAR(150);
Note that all modifications can be done in a single "pass", so this is more efficient than running n individual ALTER TABLE calls.