假设我的所有表中都有一个名为EDW_Beg_Date的公共日期列名,我需要一次检查数据库中所有表的最小和最大日期。我正在检查不同的东西,其中大部分我已研究和完成,但在最小和最大日期存货。以下是我所做的一些示例。我知道我应该使用sys.types,但我不知道的是如何让它显示每个表。让我们知道你的想法。
use EDW
go
--drop table #tempRowCount
create table #tempRowCount
(TableName varchar(255),
TotalRowCount int,
ActiveRowCount int)
--EDW_Beg_Date datetime)
--drop table #tempSQLQuery
create table #tempSQLQuery
(CommandId smallint Identity(1,1),
SQLCommand varchar(2000))
insert into #tempSQLQuery (SQLCommand)
select 'insert into #tempRowCount (TableName, TotalRowCount) select ''' + + e.name + '.' + s.name + ''' as TableName, count(*) as TotalRowCount from ' + e.name + '.' + s.name
from sys.tables s
inner join sys.schemas e
on s.schema_id = e.schema_id
where type = 'U' and e.name <> 'pdss'
select * from #tempSQLQuery
declare @CommandId smallint,
@SQLStatement varchar(2000)
While exists (select * from #tempSQLQuery)
begin
select top 1 @CommandId = CommandId, @SQLStatement = SQLCommand from #tempSQLQuery order by CommandId
execute (@SQLStatement)
delete from #tempSQLQuery where CommandId = @CommandId
end
**insert into #tempSQLQuery (SQLCommand)
select 'update #tempRowCount set ActiveRowCount = R.ActiveRowCount
from #tempRowCount A
inner join (select ''' + + e.name + '.' + s.name + ''' as TableName, Count(*) as ActiveRowCount
from ' + e.name + '.' + s.name + '
where EDW_Active_Ind = ''Y'' ) R
on A.TableName = R.TableName'**
from sys.tables s
inner join sys.schemas e
on s.schema_id = e.schema_id
inner outer join sys.columns c
on s.object_id = c.object_id
where type = 'U'
and e.name <> 'dss'
and c.name LIKE '%EDW_Active_Ind%'
While exists (select * from #tempSQLQuery)
begin
select top 1 @CommandId = CommandId, @SQLStatement = SQLCommand from #tempSQLQuery order by CommandId
execute (@SQLStatement)
delete from #tempSQLQuery where CommandId = @CommandId
end
答案 0 :(得分:0)
这是我的想法,而不是创建一个#temp表(只有一个井号),创建一个##临时表(只要会话保持可用,而不仅仅是命令)。
另外,修改一下:
insert into #tempSQLQuery (SQLCommand)
select 'insert into #tempRowCount (TableName, TotalRowCount) select ''' + + e.name + '.' + s.name + ''' as TableName, count(*) as TotalRowCount from ' + e.name + '.' + s.name
from sys.tables s
inner join sys.schemas e
on s.schema_id = e.schema_id
where type = 'U' and e.name <> 'pdss'
因此,不要插入“insert”语句,只需执行实际的“Exec('SQLStatementHere')”。看起来好像你添加了很多不必要的代码/查询来完成你的任务。