-- You can use Select * From INFORMATION_SCHEMA.Tables to table infor
-- Or just define the targeted tables
Declare @Tables table (TableName varchar(100))
Insert Into @Tables values
('TableA'),
('TableB'),
('TableC'),
('TableD'),
('TableE'),
('TableF'),
('TableG'),
('TableH')
Declare @SQL varchar(max) = '>>>'
Select @SQL = Replace(@SQL+'Union All'+char(13)+'Select TableName='''+TableName+''',Col1=sum(col1), Col2=sum(col), [RowCount]=count(*) From '+TableName+char(13),'>>>union all','')
From @Tables
Exec(@SQL)
生成されたSQLは
Select TableName='TableA',Col1=sum(col1), Col2=sum(col), [RowCount]=count(*) From TableA
Union All
Select TableName='TableB',Col1=sum(col1), Col2=sum(col), [RowCount]=count(*) From TableB
Union All
Select TableName='TableC',Col1=sum(col1), Col2=sum(col), [RowCount]=count(*) From TableC
Union All
Select TableName='TableD',Col1=sum(col1), Col2=sum(col), [RowCount]=count(*) From TableD
Union All
Select TableName='TableE',Col1=sum(col1), Col2=sum(col), [RowCount]=count(*) From TableE
Union All
Select TableName='TableF',Col1=sum(col1), Col2=sum(col), [RowCount]=count(*) From TableF
Union All
Select TableName='TableG',Col1=sum(col1), Col2=sum(col), [RowCount]=count(*) From TableG
Union All
Select TableName='TableH',Col1=sum(col1), Col2=sum(col), [RowCount]=count(*) From TableH
確かです。文字列リテラルにするだけです。 'TableA' –