Simple Cursor to Select Tables by Prefix and Creation Date

Simple Cursor to Select Tables by Prefix and Creation Date

Cursor to Select Tables by Prefix and Creation Date The cursor query below runs against a database and finds every table with a specific prefix (‘b_’, ‘delete_’). It also checks whether the table is older than a certain number of days, or was created before a certain date, and drops it. We could just as […]

July 18, 2023

Cursor to Select Tables by Prefix and Creation Date

The cursor query below runs against a database and finds every table with a specific prefix (‘b_’, ‘delete_’). It also checks whether the table is older than a certain number of days, or was created before a certain date, and drops it. We could just as easily have this run some other operation on the table instead, like a delete, a print, or an index rebuild.

 

SET NOCOUNT ON

DECLARE @lcl_name VARCHAR(100)

DECLARE cur_name CURSOR FOR

SELECT name

FROM sysobjects

WHERE type = 'U'

AND crdate <= DATEADD(m,-1,GETDATE())

AND name LIKE 'b_%'

OPEN cur_name

FETCH NEXT FROM cur_name INTO @lcl_name

WHILE @@Fetch_status = 0

BEGIN

SELECT @lcl_name = 'sp_depends' +@lcl_name

PRINT @lcl_name

-- EXEC (@lcl_name)

FETCH NEXT FROM cur_name INTO @lcl_name

END

CLOSE cur_name

DEALLOCATE cur_name

SET NOCOUNT OFF

 

SQL Server Consulting

Need expert support for SQL Server?

Our senior database team supports SQL Server performance tuning, health checks, migrations, Remote DBA services and urgent operational issues.

Explore Services

Here are a few points worth remembering about cursors.

  • Cursors are nothing more than loops, since they rely on WHILE loops internally.
  • Overusing cursors can hurt query performance, since they can consume a lot of resources.
  • Instead of using a cursor to insert one row at a time, it’s better to use set-based operations like SELECT…INSERT or INSERT INTO…SELECT.

SQL Server Consulting

Do You Need Expert Support for Your SQL Server Environment?

Aryasoft’s senior database team provides end-to-end consulting, from SQL Server performance tuning to architecture decisions.

Get SQL Server Support

4.7/5