简体   繁体   English

声明动态日期表名称以供查询参考

[英]Declare Dynamic Date Table Name for Query Reference

I am simply trying to research/obtain logic for how to dynamically (Ie GETDATE() function) call tables which are created with date stamps. 我只是试图研究/获取有关如何动态(即GETDATE()函数)使用日期戳创建的调用表的逻辑。

For example, I have tables in the database listed as such: 例如,我在数据库中列出了这样的表:

  • [dbo].[CLAIM_01.01.2018] [DBO]。[CLAIM_01.01.2018]
  • [dbo].[CLAIM_01.15.2018] [DBO]。[CLAIM_01.15.2018]
  • [dbo].[CLAIM_01.31.2018] [DBO]。[CLAIM_01.31.2018]

The logic I am thinking of would behave similar to that of setting a variable for a data element in a table (Ie SET @IMPORT_DATE = DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-1, 0)) 我正在考虑的逻辑的行为类似于为表中的数据元素设置变量的行为(即SET @IMPORT_DATE = DATEADD(MONTH,DATEDIFF(MONTH,0,GETDATE())-1,0))

Instead I would like to write a declare statement that would scan the database for a table name based on date stamp parameters. 相反,我想编写一条声明语句,该语句将根据日期戳参数在数据库中扫描表名称。 In other words, I am looking for logic that would reference the most RECENT/MAX date of the table generation (in the above examples, 1/31/2018) 换句话说,我正在寻找引用表生成的最近RECENT / MAX日期的逻辑(在上面的示例中为1/31/2018)

Please let me know if I can/should provide greater specificity for this request. 请让我知道是否可以/应该为该请求提供更多的细节。

Thank you for any assistance! 感谢您的协助!

You could use something like this. 您可以使用类似这样的东西。 Select the user tables of the database and convert the suffix to a date. 选择数据库的用户表,并将后缀转换为日期。

DECLARE @maxTable VARCHAR(255)
SET @maxTable = (
    SELECT TOP (1) name
    FROM (
        SELECT  name
            ,   DATEFROMPARTS(RIGHT(name,4), SUBSTRING(name, 7, 2), SUBSTRING(name, 10, 2)) AS dTable
        FROM    sys.tables WHERE type = 'U'
        ) AS sub
    ORDER BY sub.dTable DESC)

SELECT @maxTable

Result 结果

CLAIM_01.31.2018

If you have to keep this schema, you can select for a pattern in sys.tables , like: 如果必须保留此架构,则可以在sys.tables选择一个模式,例如:

DECLARE @IMPORT_DATE nvarchar(10) = CONVERT(nvarchar(10), GETDATE(), 4)
SELECT schemas.name + '.' + tables.name 
FROM sys.tables INNER JOIN sys.schemas 
ON tables.schema_id = schemas.schema_id 
WHERE tables.name LIKE '%' + @IMPORT_DATE + '%'

That being said, wouldn't it make more sense to have a date field in a single, static CLAIM table? 话虽这么说,在单个静态CLAIM表中具有日期字段会更有意义吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM