【问题标题】:Table join on dynamic table names动态表名上的表连接
【发布时间】:2014-10-27 10:50:39
【问题描述】:

我需要从一组表中检索 30 天内的结果。

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

例如: 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 插入临时表,然后加入结果,或者有更好的方法吗?

在正确使用的语法上几乎没有迷失。

【问题讨论】:

    标签: sql sql-server tsql join


    【解决方案1】:

    您代码中的@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 别名的子查询

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-26
      • 2013-04-02
      • 2013-10-31
      • 1970-01-01
      相关资源
      最近更新 更多