SQL:对于以给定模式开头的所有表的'union all'

时间:2018-03-12 03:47:26

标签: loops union sql-server-2014

我正在使用SQL Server 2014

我目前正在使用此查询来创建视图:

select *
from ((SELECT 'category1'   as item, * FROM itemList_category1) union all
      (SELECT 'category2'   as item, * FROM itemList_category2) union all
      (SELECT 'category3'   as item, * FROM itemList_category3)
     ) t 

适用于将所有类别组合成长列表。但是随着我的类别列表的增长,我需要手动更改此视图。

有没有办法执行相同的操作,但是通过以“itemList_”开头的所有表自动循环?

2 个答案:

答案 0 :(得分:0)

在游标中使用动态SQL。

试试这个:

declare @sql nvarchar(max)
declare @TableName nvarchar(50)

set @sql = 
'
select *
from (
'

DECLARE cursor_tables CURSOR FOR
SELECT top 3 name
FROM sys.tables
WHERE name LIKE 'itemList_%'

OPEN cursor_tables   
FETCH NEXT FROM cursor_tables INTO @TableName

WHILE @@FETCH_STATUS = 0   
BEGIN  

set @sql = @sql + '(select ' + replace(@TableName,'itemList_','') + ' as item,  * FROM ' + @TableName +  ') union all'   + CHAR(13) + CHAR(10)

  FETCH NEXT FROM cursor_tables INTO @TableName

END

CLOSE cursor_tables   
DEALLOCATE cursor_tables

set @sql = substring(@sql, 0, len(@sql)-11)

set @sql =  @sql + ')t'


print @sql

答案 1 :(得分:0)

答案非常简单,不需要游标,效率低下

--important to use correct database!
use MY_DATABASE
go
declare @query nvarchar(max) = N''
select @query += 'select ''' + name + ''' [item], * from MY_DATABASE.dbo.' + name + ' union all ' from sys.tables
where name like 'itemList%'
--remove last UNION ALL
set @query = LEFT(@query, len(@query) - 9)
EXEC @query