2014-09-03 80 views
3

我需要在30天内从一组表中检索结果。动态表名称上的表连接

该数据库似乎创建了名为monitorCounterLog的新表,并在结尾处显示日期,然后删除30天以外的任何内容。

EG: dbo.monitorCounterLog20140903用于当天在我所在位置的日期。然后将这些日期向后重复30天。

EG: 
dbo.monitorCounterLog20140903 
dbo.monitorCounterLog20140902 
dbo.monitorCounterLog20140901 
dbo.monitorCounterLog20140831 
dbo.monitorCounterLog20140830 

等等......

我需要实现类似于以下:

SELECT * 

    FROM monjtorCounterLog[30_days_worth_of_table_dates] ml 
     INNER 
     JOIN machNameTab mn 
     ON mn.agentGuid = ml.agentGuid 

WHERE [stuff...] 

这跨越30桌需要工会的所有数据。

我得到了一些动态SQL(没有这方面的经验),但是我不知道如何根据需要将它加入到其他表中。

DECLARE @mCounterLog NVARCHAR(MAX) 

    SELECT @mCounterLog = STUFF((SELECT ' UNION ALL SELECT * FROM ' +st.name AS [text()] 

     FROM sys.tables st 

    WHERE (st.name LIKE 'monitorCounterLog[0-9]%' OR st.name = 'monitorCounterLog') 
     FOR XML PATH('')), 1, 11, ''); 

     EXEC sp_executesql @mCounterLog 

我可以在这里做些什么来实现动态SQL所需的连接?

将动态SQL插入临时表中,然后加入结果,还是有更好的方法来解决这个问题?

使用正确的语法丢失很少。

回答

3

在你的代码的@mCounterLog变量将包含此:

SELECT * FROM monitorCounterLog20140903 
UNION ALL 
SELECT * FROM monitorCounterLog20140902 
UNION ALL 
SELECT * FROM monitorCounterLog20140901 
UNION ALL 
SELECT * FROM monitorCounterLog20140831 
etc. 

(为便于阅读,我已经插入换行符你的代码生成一个班轮)

因此,与其他加入吧表做到这一点传递变量之前sp_execute:

SET @mCounterLog = N'SELECT * FROM (' + @mCounterLog 
SET @mCounterLog = @mCounterLog + N') ml INNER JOIN achNameTab mn 
      ON mn.agentGuid = ml.agentGuid 
      WHERE [stuff...]' 
EXEC sp_executesql @mCounterLog 

基本上你大UNION ALL查询变成一个子查询为您ml别名

+0

太棒了,谢谢!这就是我需要的。 – Jason 2014-09-03 05:58:43