动态联合表

时间:2017-08-15 16:42:07

标签: sql-server-2008

我正在尝试创建一个动态表,我不必每个月都更新表名。因为我正在使用相同的查询(没有更改,但表格中的表名(dbo.tablename_201705)到(dbo.tablename_201706)等等。所以我创建了这个

DECLARE @TABLE_NAME VARCHAR(20) 
SET @TABLE_NAME ='dbo.GTI_'+left (convert(varchar,dateadd(mm,-3, getdate()-7), 112) ,6)

DECLARE @GTI_SQL_REPORT VARCHAR(255) 
SET @GTI_SQL_REPORT = 'select*from '+@TABLE_NAME.

从此我失去了我不知道下一步 以下是我的查询

Select 
   [CountryID], 
   COUNT([Document name]) as [inputcount], 
   MONTH([Creation Date]) AS [Creation Month], 
   Year([Creation Date]) as [Creation Year]
from 
   dbo.GTI_201705 
WHERE  
   [doc_type_product_type] not in ('CUST')
   and [Document_Source] in ('FAX','Original')  
group by 
   [CountryID],
   MONTH([Creation Date]) ,
   Year([Creation Date]) 
order by 
   [CountryID];

所以我们的想法是创建一个动态表,以便此查询将在每个月的月初运行。提前谢谢你

1 个答案:

答案 0 :(得分:1)

你很接近......你只需要将@GTI_SQL_REPORT设置为varchar(max),然后将查询设置为它。 varchar(255)不足以保存动态字符串。请注意底部的print(@GTI_SQL_REPORT)。首先执行此操作是明智的,因此您将看到正在执行的SQL。一旦您满意......然后只需将其注释掉并取消注释EXEC命令。

DECLARE @TABLE_NAME VARCHAR(20) 
SET @TABLE_NAME ='dbo.GTI_'+left (convert(varchar,dateadd(mm,-3, getdate()-7), 112) ,6)

DECLARE @GTI_SQL_REPORT VARCHAR(max) 
SET @GTI_SQL_REPORT = 
    'Select 
       [CountryID], 
       COUNT([Document name]) as [inputcount], 
       MONTH([Creation Date]) AS [Creation Month], 
       Year([Creation Date]) as [Creation Year]
    from ' + @TABLE_NAME + '
    WHERE  
       [doc_type_product_type] not in (''CUST'')
       and [Document_Source] in (''FAX'',''Original'')  
    group by 
       [CountryID],
       MONTH([Creation Date]) ,
       Year([Creation Date]) 
    order by 
   [CountryID]; '

print(@GTI_SQL_REPORT)
--exec(@GTI_SQL_REPORT)