Add a column if exists to the sql table and populate it - mysql

I am trying to add a column if it doesn't exist and populate it. My query is the following
IF NOT EXISTS (
SELECT *
FROM information_schema.COLUMNS
WHERE
TABLE_SCHEMA = 'table_name'
AND TABLE_NAME = 'adapter'
AND COLUMN_NAME = 'adapter_ip'
)
BEGIN
ALTER TABLE `adapter` ADD `adapter_ip` varchar(15) NOT NULL DEFAULT '192.168.194.57';
UPDATE `adapter` SET `adapter_ip` = '192.168.194.57';
END;
Yet every time I get an error. What exactly am I doing wrong? I tested and if I run
SELECT *
FROM information_schema.COLUMNS
WHERE
TABLE_SCHEMA = 'table_name'
AND TABLE_NAME = 'adapter'
AND COLUMN_NAME = 'adapter_ip'
by itself then it works. As soon as I put it into the if statement it gives me error at line 1 saying syntax is wrong. Because of that I even tried replacing BEGIN with THEN, and that didn't work either. Any idea what might be causing this? Thanks to anyone for their help.

I think you're missing a THEN, and an END IF after your IF <condition>
Also, this link looks good: http://www.cryer.co.uk/brian/mysql/howto_add_column_unless_exists.htm

The syntax for IF is if(test-expr,then-expr,else-expr), as detailed here: http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html

Related

MySQL: If after select(count(*) for Dropping column if exists

I already read multiples post about drop a column if exists on the forum as
if exists
(select * from INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME='tablename' AND COLUMN_NAME='columname' )
ALTER TABLE table_name DROP COLUMN column_name
But, unfortunately, none give a results on MySQL 5.7. It's because i try this:
if (select count(*) from information_schema.columns
where table_name = 'XXXX'
and column_name = 'XXXX')=1
then
ALTER TABLE `XXXX`.`XXXX` DROP COLUMN `XXXX`;
end if;
Please can someone explain me how to solve this issues?
Thanks in advance!

MYSQL Modify Column Data Type Script with Checking of Current Column Data Type

I have here a mysql script which alters my 'Job' table and changes the DESCRIPTION column data type to TEXT. However, I have this script together with all the other scripts which are sometimes run multiple times.
My question is, what do I need to add to my script so that it would check if the data type of DESCRIPTION column is already TEXT or not? This script takes too long to execute due to huge data and I don't want it to be executed again if the DESCRIPTION column has already been changed to TEXT.
ALTER TABLE Job
MODIFY DESCRIPTION TEXT;
SELECT
COLUMN_NAME, DATA_TYPE
FROM
INFORMATION_SCHEMA.COLUMNS
WHERE
TABLE_SCHEMA = 'YOUR_DB_NAME'
AND
TABLE_NAME = 'YOUR_TABLE_NAME'
AND
COLUMN_NAME = 'YOUR_COLUMN_NAME';
This will give you datatype of asked column.
Using If condition you can run your alter table command;
Here's what I did. It's a long way but it worked. It needs to be in a stored procedure. Thanks for your help #shahmanthan9. If you guys know a better way please post it here. Thanks!
DROP PROCEDURE IF EXISTS sp_JobUpdateDescriptionColumnType;
CREATE PROCEDURE sp_JobUpdateDescriptionColumnType()
DETERMINISTIC
SQL SECURITY DEFINER
COMMENT ''
BEGIN
IF NOT EXISTS( SELECT NULL
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'Job'
AND COLUMN_NAME = 'Description'
AND DATA_TYPE = 'text' )
THEN
ALTER TABLE Job
MODIFY Description TEXT;
END IF;
END;
CALL sp_JobUpdateDescriptionColumnType;
DROP PROCEDURE IF EXISTS sp_JobUpdateDescriptionColumnType;

SQL Server 2008 R2 - DROP COLUMN, INFORMATION_SCHEMA.COLUMNS and IF EXISTS

I have a column that is functionally a duplicate of another column. I want to copy the value of the surplus column to the other and then drop the extraneous column.
The problem is the script is conditional amid other changes to the database - I like to be able to restore the database to the exact state it was in via an "undo" script. This script and its corresponding "do" script are written conditionally so that they can be run repeatedly without error.
This particular block when executed a second time, fails with invalid column. It seems to think the column is still there even though both INFORMATION_SCHEMA.COLUMNS and sys.columns report no column exists.
if exists (select * from sys.objects where name = 'flint')
drop table flint
create table flint ( fred int, barny int )
go
select 1 from INFORMATION_SCHEMA.COLUMNS where COLUMN_NAME = 'barny' and TABLE_NAME = 'flint'
if exists (select 1 from INFORMATION_SCHEMA.COLUMNS where COLUMN_NAME = 'barny' and TABLE_NAME = 'flint')
begin
update flint set fred = barny
alter table flint drop column barny
end
go
select 1 from INFORMATION_SCHEMA.COLUMNS where COLUMN_NAME = 'barny' and TABLE_NAME = 'flint'
if exists (select 1 from INFORMATION_SCHEMA.COLUMNS where COLUMN_NAME = 'barny' and TABLE_NAME = 'flint')
begin
update flint set fred = barny
alter table flint drop column barny
end
go
Why does the second block get executed and fail with 'invalid column barny'?
Since your code is split into batches by the GO delimiters, the second block is only submitted after the column has been dropped by the first block. The second block does not get executed but it does get compiled and bound to database objects. Hence name resolution fails and you get the error message. The message is coming from the parser, not the database engine.
Bizarrely, if you remove all the GOs it will fail at the second SELECT 1.. with the same error.
It's to do with SQL Server batching but damned if I can figure it out why at the moment. Remove the GO from between the blocks and it works as expected. My guess is that the column is dropped during the second batch but the third batch has already been compiled ready to send so it only fails when it tries to execute on the server. I'm going to do some reading on this because it's a neat little gotcha.
D'oh! The parser is looking at the references to the removed column in the block before we know the result of EXISTS. So if I use dynamic SQL, all is well.
if exists (select 1 from INFORMATION_SCHEMA.COLUMNS where COLUMN_NAME = 'barny' and TABLE_NAME = 'flint')
begin
declare #q nchar(100)
select #q='update flint set fred = barny;
alter table flint drop column barny'
exec sp_executesql #q
end
go
Thanks Michael and Steve!

MySQL String, check is column exists

I am creating something where a column is created for the current date if it does not exist. This is the current query to check for a column name and create one if it does not exist. The variable is $date And this does not work, please can somebody suggest what is wrong with it.
$result = mysqli_query($con,"
IF NOT EXISTS (
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Scouts' AND COLUMN_NAME = '$date'
)
BEGIN
ALTER TABLE Scouts ADD '$date' VARCHAR( 255 )
END
");
SQL injection is not a problem as it is only being hosted on a local machine.
Sorry if it wasn't clear at first.

Delete row if table exists SQL

I have a script that drops a load of tables using DROP TABLE IF EXISTS, this works.
There is also a delete in this script to DELETE a row from another table that I do not manage. This table may or may not exist.Is there any to check the table exists before attempting to delete a row?
this needs to work for MYSQL and SQLServer
thanks
Alex
To check in SQL SERVER,
IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'TheSchema' AND TABLE_NAME = 'TheTable'))
BEGIN
--Do Stuff
END
To check in mysql:
You simply count:
SELECT COUNT(*)
FROM information_schema.tables
WHERE table_schema = '[database name]'
AND table_name = '[table name]';
This one deletes the row and does not complain if it can't.
DELETE IGNORE FROM table WHERE id=1
source here.
For SQL Server: You could use:
IF OBJECT_ID('tablename','U') IS NOT NULL
I dont think you'll find a common syntax between SQL server and my SQL. I mean, you can check if the table exsits on SQL Server using something like:
if exists(select * from sys.objects where name like 'table_name')
but mySql would have its own catalog.
Unless you write a script like:
if (sql_server) then
if exists(select * from sys.objects where name like 'table_name')
else --mySQl
--execute the mysql script
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TABLE_NAME]') AND type in (N'U'))
It seems to me right the first item in the "Related" column on the right side answers your question.... Check if table exists in SQL Server
For MySQL
show tables like "test1";
For SQL Server
SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'testSchema' AND TABLE_NAME = 'test1'
A question you want to ask yourself (in terms of database design): Why are you trying to delete rows from a table you are not sure exists? If it doesn't, but you expect it does, wouldn't you rather create the table than not delete it?
Anyway, Chris Gesslers answer does exactly what you are asking in SQL Server, but there is some smell here.
The construct in MySQL you can use is
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'databasename'
AND table_name = 'tablename'
and check for results
you can use bellow code:
DECLARE #TABLENAME VARCHAR(20)='TableName';
IF (OBJECT_ID(#TABLENAME) IS NOT NULL )
BEGIN
execute(N'TRUNCATE TABLE ' + #TABLENAME + '' );
END
ELSE
BEGIN
PRINT 'Table NOT Exists'
END