2013-11-15 53 views
0

假設我的所有表中都有一個通用日期列名稱,名爲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

這是我的想法,而不是創建一個#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' 

所以不是插入你的 「插入」 語句,只是做一個實際的 「EXEC( 'SQLStatementHere')」。看起來好像你添加了很多不必要的代碼/查詢來完成你的任務。

+0

@ ganders,一旦我得到我需要的所有代碼,我肯定會處理性能問題。感謝您的貢獻。 – user2994652

相關問題