When you drop a table, you are
deleting it from the database. When you perform this action, you are
also deleting the table data, indexes, triggers, constraints, and
permissions that were defined on the table. In certain circumstances,
you are not allowed to drop a table. For example, if your table is
referenced by another table via a foreign key constraint, the foreign
key constraint must be removed from the referring table first before
the table in question can be deleted. Also, any stored procedures or
views that reference the table will need to be dropped or changed
before the table in question can be dropped.
To help illustrate deleting a table, let’s create two tables: Customers
and Accounts
. The Accounts
table will contain a column customer_id
that references the customer_id
column in the Customers
table. The script to create these tables is as follows:
CREATE TABLE Customers
(customer_id INT PRIMARY KEY,
customer_name NVARCHAR(50) NOT NULL)
GO
CREATE TABLE Accounts
(customer_id INT REFERENCES Customers(customer_id),
account_balance MONEY)
GO
To drop the Customers
table using
SSMS, simply right-click Customers in Object Explorer and select
Delete. This will launch the Delete Object dialog box shown in Figure 1.
Figure 1. Delete Object dialog box
If you click OK to delete, you will get an
error stating “Drop failed for Table ‘dbo.Customers’.
(Microsoft.SqlServer.Smo).” If you click the error link, you will find
more details, including the following text: “Could not drop object
‘dbo.Customers’ because it is referenced by a FOREIGN KEY constraint.
(Microsoft SQL Server, Error: 3726).” Since the Customers
table is referenced by the Accounts
table, you can’t drop it until you address the foreign key reference.
To determine these issues before you actually issue the drop command,
you can click the Show Dependencies button. This will launch the
Customers Dependencies dialog box shown in Figure 2.
Figure 2. Customers Dependencies dialog box
Figure 2 clearly shows that the Accounts
table references the Customers
table.
The DDL statement for dropping a table is the DROP TABLE
statement. To drop both tables, use the following script:
DROP TABLE Accounts
GO
DROP TABLE Customers
GO