0

我的 SQL Server 2008 R2 数据库中有一组表,它们都具有相同的列。

我需要SELECTUNION这些表。我可以SELECT这样的表格:

SELECT TABLE_NAME FROM information_schema.tables
where (TABLE_NAME like '%_CH1' or TABLE_NAME like '%_CH0')
and TABLE_NAME not like '%test%'

我现在需要的是SELECT Column1, Column2, Column3从该列表中的第一个人开始,UNION SELECT Column1, Column2, Column3从该列表中的下一个人开始,依此类推。

我怎么做?

4

2 回答 2

4

动态查询示例;

--CREATE TABLE Utable1 (Col1 INT, Col2 INT, Col3 INT)
--CREATE TABLE Utable2 (Col1 INT, Col2 INT, Col3 INT)
--CREATE TABLE Utable3 (Col1 INT, Col2 INT, Col3 INT)


DECLARE  @SelectClause  VARCHAR(100)    = 'SELECT Col1, Col2, Col3'
        ,@Query         VARCHAR(1000)   = '' 

SELECT @Query = @Query + @SelectClause + ' FROM ' + TABLE_NAME + ' UNION ALL '
FROM INFORMATION_SCHEMA.TABLES
WHERE (TABLE_NAME LIKE '%_CH1' OR TABLE_NAME LIKE '%_CH0')
AND TABLE_NAME NOT LIKE '%test%'

SELECT @Query = LEFT(@Query, LEN(@Query) - LEN(' UNION ALL '))

EXEC (@Query)
于 2013-01-04T16:01:39.243 回答
2

如果列名相同, @MarkD 的答案会很好,但如果列名不同,那么您将需要查询INFORMATION_SCHEMA.COLUMNS以获取列名。

这是应该也可以工作的版本:

select row_number() over(order by (select 1)) id, table_name
into #tempTables
from information_schema.tables
where table_name like 'Table%'

declare @tempColumns table
(
    id int,
    column_name varchar(50),
    table_name varchar(50)
) 

declare @query varchar(max) = ''
declare @rownum int = 1
declare @maxrownum int = (select max(id) from #temptables)
declare @table varchar(50)

declare @colrow int = 1

while @rownum <= @maxrownum
  begin
    set @table = (select TABLE_NAME from #tempTables where id = @rownum)

    set @query = @query + ' SELECT '

    insert into @tempColumns    
    select row_number() over(order by (select 1)) id, COLUMN_NAME, @table
    from INFORMATION_SCHEMA.COLUMNS
    where TABLE_NAME = @table
        and ORDINAL_POSITION in (1, 2, 3)

        -- reset colrow to 1
        set @colrow = 1

        while @colrow <= 3
            begin

                set @query = @query + (select Column_name 
                                        from @tempColumns 
                                        where id = @colrow
                                            and table_name = @table) + ' as Col' + CAST(@colrow as varchar(50))

                if @colrow < 3
                    set @query = @query + ', '

                if @colrow <= 3
                    set @colrow = @colrow + 1

            end

    set @query = @query + ' FROM ' + @table

    if @rownum < @maxrownum
        set @query = @query + ' UNION ALL '

    if @rownum <= @maxrownum
        set @rownum = @rownum + 1
  end

exec(@query)

请参阅带有演示的 SQL Fiddle

于 2013-01-04T16:27:21.580 回答