SQL Statement That Will Get Table Schema And Created Date

2.6k views Asked by At

I am trying to create a SQL Statement that will return the table schema name and the if the data was created a day ago.

This will create the SQL Statement with the table schema name:

DECLARE @SqlStatement VARCHAR(MAX)
SELECT @SqlStatement = 
    COALESCE(@SqlStatement, '') + 'DROP TABLE [TMP].' + QUOTENAME(TABLE_NAME) + ';' + CHAR(13)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'TMP'

PRINT @SqlStatement

How do I add in the where clause if the table was created a day ago all in the same statement?

1

There are 1 answers

4
sgeddes On BEST ANSWER

The create_date field is stored in sys.tables. You can then join back to sys.schemas to get the schema name.

Something like this:

declare @SqlStatement varchar(max)
select @SqlStatement = COALESCE(@SqlStatement, '') + 'DROP TABLE [TMP].' + QUOTENAME(t.name) + ';' + CHAR(13)
from sys.tables t 
    join sys.schemas s on t.schema_id = s.schema_id 
where s.name = 'TMP'
    and t.create_date > dateadd(day,-1,getdate())
print @SqlStatement