MySQL String, check is column exists - mysql

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.

Related

How to delete all tables that have 1-2 rows

Im having a database which is over 60k tables and i want to delete all the tables that have 1 or 2 rows.
You can use the below code in SQL Server 2012. It will delete all the tables which is having row_count less than 3.
USE [YourDB]
GO
DECLARE #Max int, #Count int,#Table_Name Varchar(20)
SET #Max =0
IF OBJECT_ID('tempdb..#temp') IS NOT NULL
DROP TABLE #temp
CREATE TABLE #temp
(
table_name sysname ,
row_count INT,
reserved_size VARCHAR(50),
data_size VARCHAR(50),
index_size VARCHAR(50),
unused_size VARCHAR(50)
)
IF OBJECT_ID('tempdb..#temp1') IS NOT NULL
DROP TABLE #temp1
CREATE TABLE #temp1
(
ID int IDENTITY(1,1),
table_name sysname ,
row_count INT
)
SET NOCOUNT ON
INSERT #temp
EXEC sp_msforeachtable 'sp_spaceused ''?'''
INSERT INTO #temp1
SELECT a.table_name,
a.row_count
FROM #temp a
INNER JOIN information_schema.columns b
ON a.table_name collate database_default
= b.table_name collate database_default
GROUP BY a.table_name, a.row_count
HAVING a.row_count <3
SET #Count =(SELECT COUNT(*) FROM #temp1)
WHILE #Count > #Max
BEGIN
SET #Max = #Max +1
SET #Table_Name = (SELECT table_name FROM #temp1 WHERE ID = #Max)
EXEC('DROP TABLE ' +#Table_Name)
END
Use a MySQL-GUI, order by number of rows and drop all tables with 1-2 rows. it is as easy as deleting files in a windows folder. this
would take ~10 seconds + sort and drop time
or
Select table names of tables with 1-2 rows from information_schemas, load into an excel file and build your drop statements. takes around 2-5 minutes + drop time
or
Build a stored procedure that uses a Cursor to parse all the relevant table names into variables of your drop statement (like Hansa mentioned). this makes sense if you want to repeat your process from time to time. takes around 1-12 hours for beginners (depending on knowledge level) + drop time
Since logging in on SO probably took more time than solution 1 would,
i would recommend that solution.
In case you want to spend more time , the following query will show all table names for tables with 1-2 rows:
SELECT table_schema, table_name From information_schema.tables
WHERE table_schema='your_schema' # use your table_schema here
AND table_rows BETWEEN 1 and 2 ;
I would do it within some application side logic, using a programming language of your choice (which offers a mysql API).
Get all table names, described here, grouping them by table names
e.g. this could look something like:
SELECT COUNT(table_rows), table_name
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = '{your_db}'
GROUP BY table_name;
(this is not tested, but to give you a basic idea...)
Execute a delete statement for the tables with rowcount 2 or lower. Should be an easy task as soon as you got the results in your programming language (btw SQL statement to delete them is "DROP TABLE")
Note: I think it should be also possible using a SQL cursor, but as I said I would prefer the above solution.
You can try this.
First take all the table names from the database.
After getting all the table names put them in a array and execute a foreach loop that checks the num of rows for each table, something like this
$tables = array();
foreach ($tables as $table_name){
$query = "select * from '$table_name'";
$result = mysqli_query($dbCon, $query);
$num_rows = mysql_num_rows($result);
if($num_rows < 3){
$delete = "drop table $table_name";
$res_del = mysqli_query($dbCon, $delete);
echo $table_name." Deleted";
}
}
You probably cant do this with 1 SQL Statement unless you are using stored procedures (see below).
You will need to select all tables in MySQL with a programming language (e.g. Java with JDBC) using the following statement:
select TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_ROWS <= 2 AND TABLE_ROWS >= 1
Then you can use the results in the programming languge to issue drop Statements for each result record in a loop:
drop table <tablename>
For doing this with a stored procedure (i.e. without a programming language)
see the third comment on this page: MySQL Reference Drop Table.
Of course you will need to adapt this to your needs because this example does not select tables by their row numbers but by their names.

SQL add new columns ignoring duplicates

We have quite a few databases, and we're trying to run upgrade scripts on all of them to bring them up to date - as such, they all have different columns and tables.
We want to add new tables and columns if they arent already present, so for instance
CREATE TABLE IF NOT EXISTS `orders` ( `id` INT (11) NOT NULL ,
`value` VARCHAR (50) , `designId` INT (11) , PRIMARY KEY ( `id`));
That works, but we're looking for the same kind of solution for columns. Our current solution throws Error Code: 1060 - Duplicate column name.
ALTER TABLE `orders` ADD COLUMN `customer` INT (1) NULL;
I've tried the following from garry passarella, but i get an error claiming incorrect sql syntax:
IF NOT EXISTS(SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'orders' AND COLUMN_NAME = 'customer')
BEGIN ALTER TABLE orders
ADD customer BIT DEFAULT NULL
END
If there is something we can use to get each line to ignore duplicates, or get the entire script to ignore error code 1060, it would be much appreciated.
The if ... begin ... end is SQL Server syntax. For MySQL, it's more like if ... then ... end if:
if not exists (select * from information_schema.columns
where column_name = 'customer' and table_name = 'orders') then
alter table orders add customer int(1) null;
end if
In reply to your comment: in MySQL, you can't type compound statements at the command line. They have to be in a function or stored procedure. For example:
drop procedure if exists sp_addcolumn;
delimiter //
create procedure sp_addcolumn()
begin
if not exists (select * from INFORMATION_SCHEMA.COLUMNS
where table_name = 'orders' and column_name = 'customer') then
alter table `orders` add column `customer` int(1) null;
end if;
end//
delimiter ;
call sp_addcolumn;
There is an open request on the MySQL bug tracker to allow if statements outside stored procedures. It's current status is Needs Triage.

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

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

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

Set all the columns of a mysql table to a particular value

hIs there any way to update all the columns of a mysql table for a particular record in one go to a particular value.
For e.g. I have a table that has around 70 columns , and they are by default set to 0 at the time of creating the table,when I add a new record via PHPmyadmin by just filling in one or two values and submitting it all the other fields are set to 0 , but I want to set all the fields to 1
many times ,so I need to set all the columns to 1 individually via PHPmyadmin
To speed-en up the process and
I tried
UPDATE tablename SET * = '1' WHERE id = '2' , but it does not work.
If anyone can provide a solution on similar lines , it would be great.
EDIT:
Is there a way without specifying all the 70 columns in the SQL statement? that what I am looking for. I do know how to update normally specifying columns in the SQL statement. Thank you.
If you are looking for a way to update all 70 columns to a single value with a short, simple statement, then I recommend that you write a stored procedure to do the update. That way you only need to write out the full update syntax once, and can re-use it over and over by calling the stored procedure.
CREATE PROCEDURE update_all_columns (p_new_value SMALLINT, p_id INT) ...
CALL update_all_columns(1,2);
Another trick is to use the information_schema.columns table to generate the update statement, making it less tedious to code the stored procedure.
Something like this:
SELECT concat('UPDATE ',
table_name,
' SET ',
group_concat(column_name separator ' = p_new_value, '),
' = p_new_value',
' WHERE id = p_id;') as sql_stmt
FROM information_schema.columns
WHERE table_schema = 'your_schema'
AND table_name = 'tablename'
AND column_name != 'id'
You have to name each column in an update statement.