是否可以添加表名以用于审计目的,例如,如果我正在运行查询:
Select TableA, sum(col1), sum(col1), count(*) As rowcount
from TableA
然而,表中没有Name
这样的列TableA
,但无论如何都要以某种方式将其引入查询?例如,使用sys表或信息模式并以这种方式引入表名?
此外,我正在做大量的表格,例如从TableA
到TableH
如何使用TSQL为每个表执行此操作?
谢谢
答案 0 :(得分:1)
-- 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 Generated是
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
答案 1 :(得分:0)
您可以添加一个恰好与表名匹配的字符串。这需要单引号:
Select 'TableA' as tablename, sum(col1), sum(col1), count(*) As rowcount
from TableA;
如果您想以更规范的方式执行此操作,则需要动态SQL。
declare @tablename varchar(255);
set @tablename = 'tableA';
declare @sql nvarchar(max);
set @sql = 'Select '@tablename' as tablename, sum(col1), sum(col1), count(*) As rowcount
from @tablename';
set @sql = replace(@sql, '@tablename', @tablename);
exec sp_executesql @sql;
这是基本代码。你需要一个while
循环来浏览你想到的所有表格。