我正在尝试创建一个动态表,这样我就不必每月更新表名。由于我使用的是相同的查询(没有更改,只是将(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];因此,我们的想法是创建一个动态表,以便在每个月初运行此查询。提前谢谢你
发布于 2017-08-16 00:51:22
你们很接近..。您只需将@GTI_SQL_REPORT设置为varchar(max),然后将查询设置为它。varchar(255)不足以容纳您的动态字符串。请注意bottm上的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)https://stackoverflow.com/questions/45697453
复制相似问题