2010-09-15 43 views
2

我一直在試圖找出每個表中被禁用的行的總數。 在我的數據庫中,我有20列IsActive列的表。查詢根據列名查找表的行數?

我曾嘗試下面的光標,但它越來越錯誤說無效的對象名稱@Namee。

Create table #t 
(
NoOfRows bigint, 
) 

Declare @Namee Varchar(500) 
Declare @GetName Cursor 
Set  @Getname = Cursor for 
Select table_name from information_Schema.columns 
where column_name='isactive'Open @Getname 
Fetch Next From @Getname into @Namee 
While @@Fetch_Status=0 
Begin 
insert into #t Select count(*) from @Namee where isactive=0 
Fetch Next From @Getname into @Namee 
End 
Close @GetName 
Deallocate @GetName 
select * from #t 

回答

0

更換

insert into #t Select count(*) from @Namee where isactive=0 

exec ('insert into #t Select count(*) from ' + @Namee + ' where isactive=0') 
+0

感謝百萬Preet的工作。 – Simhadri 2010-09-15 21:57:18

0

根據你的示例查詢,這應該工作。這也將是比使用光標

select 
    OBJECT_NAME(c.object_id) as table_name 
, p.row_count 
from sys.columns c 
join sys.dm_db_partition_stats p 
    on c.object_id = p.object_id 
    and p.index_id < 2 
where c.name = 'IsActive' 
+1

這隻會返回每個這樣的表的rowcount。但他需要一個過濾結果。 – 2010-09-15 21:35:35

+0

你是對的。我誤解了這個問題。你的答案是我想要的。 – 2010-09-15 21:39:38

2

嘗試快得多這樣的:

exec sp_msforeachtable ' 
if exists(
select * from sys.tables as t 
join sys.columns as c on t.object_id = c.object_id 
where t.name = ''?'' and c.name = ''IsActive'') 

select count(*) 
from [?] 
where isactive=0' 
1

雖然我沒有測試過,我會選擇Mike或Denis的swer。

然而,這裏的問題是線路:

insert into #t Select count(*) from @Namee where isactive=0 

您使用@Namee就像它是一個表,但它確實是一個表名的字符串。你將不得不動態地建立SQL,然後執行它:

exec 'insert into #t select count(*) from ' + @Namee + ' where isactive=0'