Skip to content
Advertisement

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

Advertisement

Answer

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]';
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement