Home > Net >  Defining SQL Server table name from date
Defining SQL Server table name from date

Time:06-07

My SQL Server database has tables named after the load date in this format

## FROM [GL_202206].[dbo].[GL_ACCOUNT_20220602].

I have done a query that can generate a similar sting as the table name as below:

SELECT 
    CONCAT('[GL_', YEAR(GETDATE()), FORMAT (GETDATE(), 'MM'),
           '].[dbo].[GL_ACCOUNT_', CONVERT(CHAR(8), GETDATE(), 112), ']')

How can I get the string to make the table name in the query?

Say

SELECT 
    ACCOUNTID, ACCOUNTNAME 
FROM 
    [GL_202206].[dbo].[GL_ACCOUNT_20220602]

CodePudding user response:

Your SQL is correct, you only need to execute it.

declare @sql nvarchar(max) = null;
SELECT @sql = 'select ACCOUNTID, ACCOUNTNAME from '  
    CONCAT('[GL_', YEAR(GETDATE()), FORMAT (GETDATE(), 'MM'),
           '].[dbo].[GL_ACCOUNT_', CONVERT(CHAR(8), GETDATE(), 112), ']');
exec (@sql)
  • Related