When working with large databases in SQL Server, it is often necessary to find tables that follow a specific naming pattern. One such scenario is identifying all tables whose names end with a specific suffix. This can be useful for database maintenance, debugging, auditing, or dynamically querying related data.
This tutorial covers multiple ways to achieve this in SQL Server, catering to both beginners and advanced users.
Finding tables with a specific suffix can help in:
_archive
._temp
.SQL Server provides multiple ways to search for table names that end with a specific suffix. Below are three commonly used methods.
INFORMATION_SCHEMA.TABLES
The INFORMATION_SCHEMA.TABLES
view contains metadata about all tables in the database, making it a straightforward option to find tables by suffix.
SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME LIKE '%_archive';
sys.tables
The sys.tables
system catalog view provides another method to retrieve table names based on suffix filtering.
SELECT name
FROM sys.tables
WHERE name LIKE '%_archive';
sys.objects
The sys.objects
system catalog view stores all database objects, including tables. This method is particularly useful if you need more metadata about the tables.
SELECT name
FROM sys.objects
WHERE type = 'U'
AND name LIKE '%_archive';
Here, 'U
' represents user tables.
Let’s consider a database with the following tables:
sales_archive
customer_archive
orders
employee_temp
If we execute the following query:
SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME LIKE '%_archive';
We get:
TABLE_NAME
------------
sales_archive
customer_archive
This confirms that only the tables ending with _archive
are retrieved.
Organizations often store old data in archive tables for auditing purposes. You can quickly list all archive tables using:
SELECT name
FROM sys.tables
WHERE name LIKE '%_backup';
Developers sometimes create temporary tables ending with _temp
for staging data. To find such tables:
SELECT name
FROM sys.tables
WHERE name LIKE '%_temp';
If you need to drop all tables ending with _temp
, you can generate dynamic SQL:
DECLARE @sql NVARCHAR(MAX) = '';
SELECT @sql = @sql + 'DROP TABLE ' + name + '; '
FROM sys.tables
WHERE name LIKE '%_temp';
EXEC sp_executesql @sql;
INFORMATION_SCHEMA
.TABLES
, sys.tables
, and sys.objects
.LIKE
operator is essential for pattern matching in table names.Finding tables with a specific suffix in SQL Server is a crucial task for database administrators and developers. Using INFORMATION_SCHEMA.TABLES
, sys.tables
, and sys.objects
, we can efficiently retrieve and manage tables based on naming conventions. These techniques help in organizing and optimizing database operations while making querying more efficient.
Comments