Delete row if table exists SQL

Solution 1

For SQL Server: You could use:

IF OBJECT_ID('tablename','U') IS NOT NULL

Solution 2

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

Solution 3

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TABLE_NAME]') AND type in (N'U'))

Solution 4

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

Solution 5

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

Author by


Updated on September 15, 2020


  • Admin
    Admin almost 2 years