The DROP TABLE command in SQL Server will do as it suggests and drops a table. This post is to share an example of using the command, including the IF EXISTS argument which allows us to conditionally drop the table (does not cause an error).
DROP TABLE IF EXISTS works on SQL Server 2016 and above.
For more information on this, as ever you should check out the Microsoft Documentation on anything and everything you do on their products.
In the following example, I’m creating a new table followed by running the DROP TABLE IF EXISTS command. I run the DROP statement twice to show & explain the execution error part.
# create a test table CREATE TABLE demoTable (r_id INT, r_name VARCHAR(100), r_description VARCHAR(200)); # drop the above table DROP TABLE IF EXISTS T1; # drop the table again, no execution errors / script will continue DROP TABLE IF EXISTS T1;
You can also get information from system tables to verify if a SQL Object exists or not. This is just one way.
Random fact: In other SQL platforms the alternative to the DROP TABLE IF EXISTS command is DROP TABLE <TableName> CASCADE;