Delete row if table exists SQL - mysql

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

Related

Using MYSQL, How do I query a table only if it exists already?

Im writing a migration and Im trying to query a table only if it exists in the db. In some envs it will exist and in others it wont which is why i want to check if it exists. The table of interest is called OLD_PASSWORD. I do the following.
SELECT ID, PASSWORD
FROM OLD_PASSWORD;
WHERE EXISTS
(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'OLD_PASSWORD);
This fails '.dbcSQLSyntaxErrorException: Table "USER_OLD_PASSWORDS" not found;' which makes sense because it wont exist in some envs.
I also tried something like
IF (EXISTS (SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = 'OLD_PASSWORD'))
BEGIN
SELECT ID,
PASSWORD
FROM OLD_PASSWORD
END
but it's not compatible with mysql.
Best approach was to query INFORMATION_SCHEMA.TABLES from Java, and then do the query from OLD_PASSWORD if it returns something.
You forgot the ' sign at the end of query before the ).
Nonetheless, this is cartesian select. Use in instead. i.e
password in (select password ...) etc.

MySQL query where column may be missing

I have a Microsoft stored procedure that queries two MySQL databases using OpenQuery. The two MySQL databases should be have the same schemas, so I can run the same query on both.
However, we will soon alter the MySQL schemas, and add a column to a table. But the two MySQL databases won't happen at the same time, and I don't know the exact date of the releases.
I therefore want to write the query so that if the new column exists, then I use it in my select. If not, then I use a default value.
Is this possible? (That is have a query that handles differences in the table schema?)
(Not to be confused with 'coelesce' where the field definitely exists, but is simply null.)
You can use the following SELECT statement:
SELECT *
FROM information_schema.COLUMNS
WHERE
TABLE_SCHEMA = 'database name' AND TABLE_NAME = 'your table name'
AND COLUMN_NAME = 'the column name you want to check for'
If the above returns a value, your column is there. If not, then run your alternative SELECT statement
Updated statement:
IF EXISTS (SELECT *
FROM OPENQUERY(servername, 'SELECT *
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = ''database name''
AND TABLE_NAME = ''your table name''
AND COLUMN_NAME = ''the column name you want to check for'' ))

How can I write a sql query to check if a particular table exists in a database?

I know how to use queries but I've never had to use one for this particular tasks .. I know about the SHOW TABLES; command .. How can I write a query to check if a particular table exists in a MYSQL database .. For example , a query that checks if table MEMBERS exists in database called USERS ??
You can use INFORMATION_SCHEMA.TABLES
USE USERS;
SELECT * FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = 'MEMBERS'
Searching Table:
select * from
information_schema.tables
where table_name like '%MEMBERS%'
Searching Column:
select * from
information_schema.columns
where table_name like '%COLUMN%'

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

validate if table exists while selecting and inserting SQL Server

Hello I have a dynamic query like
SET #template = 'SELECT x AS X,... INTO temporalTable FROM' + #table_name
Then I execute it
EXEC (#template)
How do I validate if temporalTable
already exists, if so, drop it?
Just use OBJECT_ID
IF OBJECT_ID('temporalTable') IS NOT NULL
DROP TABLE temporalTable
No need to query any tables or do any aggregations.
Use information schema or sp_help function.
I would prefer information schema since it's SQL ANSI and you can port the code to other databases:
select count(1)
from information_schema.tables
where table_name = 'temporalTable';
sys.tables is a SQLServer specific option similar to inforamtion schema that you can also explore.
IF EXISTS (SELECT 1
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE='BASE TABLE'
AND TABLE_NAME='tablename')
SELECT 'tablename exists.'
ELSE
SELECT 'tablename does not exist.'