I am trying to dynamically select tables from my database based on the name of the table, which in turn is based on the creation date. For example, tables may be named "tableA20110305" or "tableB20110305", which indicates that the tables were created on March 05, 2011.
I am trying to write a query that selects all tables so named, created before a certain cut-off date (1 year ago), and combine them in the instructions of the DROP TABLE command in a table variable. The select statement is as follows.
DECLARE @cutoffDate datetime = CONVERT(DATETIME, DATEADD(YEAR,-1,GETDATE()), 112)
SELECT 'DROP TABLE "' + TABLE_NAME + '"' AS 'Command'
FROM INFORMATION_SCHEMA.TABLES
WHERE (TABLE_NAME LIKE 'tableA%' OR TABLE_NAME LIKE 'tableB%')
AND (CONVERT(DATETIME, SUBSTRING(TABLE_NAME, 7, 8), 112) < @cutoffDate)
ORDER BY Command DESC
However, when I execute this SQL, I see the following error:
Msg 241, 16, 1, 14 / .
... SQL, :
SELECT CONVERT(DATETIME, SUBSTRING('tableA20110305', 7, 8), 112)
, .
.