SQL- UNION ALL a large number of tables

前端 未结 4 1670
萌比男神i
萌比男神i 2021-01-27 07:39

I have a large number of tables (some thousands) containing similar data. I would like to run some reports from these. The table names are similar, so I can get a list of table

相关标签:
4条回答
  • 2021-01-27 07:57

    You can do this with Dynamic SQL

    Declare @SQL varchar(max) =''
    Select @SQL = @SQL +'Union All Select * From '+Table_Name+' ' 
      FROM INFORMATION_SCHEMA.TABLES
      WHERE TABLE_NAME LIKE 'TableNamePrefix%'
      ORDER BY TABLE_NAME
    Set @SQL = Stuff(@SQL,1,10,'')
    Exec(@SQL)
    
    0 讨论(0)
  • 2021-01-27 08:09
    select 'select * from  '+TABLE_NAME +' union all'
    FROM
     INFORMATION_SCHEMA.TABLES
    WHERE TABLE_NAME LIKE '%chd%'
    ORDER BY TABLE_NAME
    

    remove last union all

    0 讨论(0)
  • 2021-01-27 08:15

    All these tables have the same data types and number of columns, because if this not the case then you will not be able to use UNION sentences, however, it's very strange to merge all the information in this way, could you put some examples to clarify it.

    0 讨论(0)
  • 2021-01-27 08:18

    using your pattern on table name - i got somewhere with

    DECLARE @SQL nvarchar(max);
    
    select @SQL =  COALESCE(@SQL , '') + 'SELECT * FROM [' +  TABLE_NAME + ']  UNION ALL ' 
    FROM INFORMATION_SCHEMA.TABLES where TABLE_NAME LIKE '%employeedet%';
    
    SELECT @SQL = LEFT(@SQL, LEN(@SQL) - 11);
    
    print @SQL;
    
    0 讨论(0)
提交回复
热议问题