显示单独查询返回的表中的所有行的视图

时间:2016-06-09 09:16:49

标签: sql sql-server

需要显示多个表中的所有行。要包含的表来自单独的查询以确保。因此,我们知道数据源自何处,必须添加包含表名的新列。

要包含在其中的表必须是动态的,以减少维护,因此会自动包含新创建的表。 要选择表,我创建了这个查询:

select TABLE_NAME
from INFORMATION_SCHEMA.COLUMNS
where COLUMN_NAME = 'contact_info_type' 
and TABLE_NAME NOT LIKE '%test%' 
and TABLE_NAME NOT LIKE '%_STAGING'

测试' contact_info_type'列是为了确保表具有预期的结构。所有这些表都完全相同。

但是,如何将这些结果传递给新的选择语句?

我尝试了这个,它产生了重复的结果,并且不会停止处理。它还缺少在表名中添加的额外列

declare @tableNames nvarchar(max)
select  @tableNames = COALESCE(@tableNames + ', ', '')  + Cast(TABLE_NAME as varchar) from INFORMATION_SCHEMA.COLUMNS
where COLUMN_NAME = 'contact_info_type' and TABLE_NAME not like '%_STAGING' and TABLE_NAME like '%test%'
select @tableNames
declare @sqlText nvarchar(max)
set @sqlText = ''
select @sqlText = @sqlText + 'SELECT * from ' + @tableNames where person = 'Joe'
select @sqlText

每个表格都会包含几千行,但条件(名称=' Joe')会将结果限制在100左右。

运行Server 2008 R2 SP3(10.50)。

1 个答案:

答案 0 :(得分:1)

这个查询可能会对你有帮助,

但您需要在@results表中添加所需的其他列。

DECLARE @tables TABLE  (tableName VARCHAR(1000), nmbr INT IDENTITY(1,1))
DECLARE @results TABLE (person varchar(500), tablename varchar(1000))
DECLARE @i INT,
    @tableName varchar(1000),
    @sql varchar(500)

INSERT INTO @tables
SELECT DISTINCT TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME = 'contact_info_type' 
    AND TABLE_NAME NOT LIKE '%test%' 
    AND TABLE_NAME NOT LIKE '%_STAGING'

SELECT @i = MAX(nmbr)
FROM @tables AS t

WHILE (@i > 0)
BEGIN

    SELECT @tableName = tablename
    FROM @tables
    WHERE nmbr = @i

    SET @sql = 'SELECT person, '''+@tablename +''' as tablename
                FROM '+ @tableName +'
                WHERE person = ''joe'''

    INSERT INTO @results
    EXEC (@sql)

    SET @i = @i - 1

END

SELECT * FROM @results