Sql 动态表名上的表联接
我需要在30天内从一组表中检索结果 数据库似乎创建了名为monitorCounterLog的新表,表的末尾有日期,然后删除30天以外的任何内容 例如: dbo.monitorCounterLog20140903用于我所在地的今天的日期。然后,对每个日期向后重复这些操作30天Sql 动态表名上的表联接,sql,sql-server,tsql,join,Sql,Sql Server,Tsql,Join,我需要在30天内从一组表中检索结果 数据库似乎创建了名为monitorCounterLog的新表,表的末尾有日期,然后删除30天以外的任何内容 例如: dbo.monitorCounterLog20140903用于我所在地的今天的日期。然后,对每个日期向后重复这些操作30天 EG: dbo.monitorCounterLog20140903 dbo.monitorCounterLog20140902 dbo.monitorCounterLog20140901 dbo.monitorCounter
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插入临时表,然后根据结果进行连接,或者有更好的方法来实现这一点吗
在使用正确的语法方面几乎没有什么损失。代码中的
@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
别名的子查询