我一直试图找出每个表中已取消激活的总行数。 在我的数据库中,我有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 :(得分: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 :(得分:1)
虽然我没有对它们进行测试,但我会选择迈克或丹尼斯的答案。
然而,这里的问题是:
insert into #t Select count(*) from @Namee where isactive=0
你正在使用@Namee,就像它是一个表,但它实际上是一个带有表名的字符串。您必须动态构建SQL然后执行它:
exec 'insert into #t select count(*) from ' + @Namee + ' where isactive=0'
答案 2 :(得分: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'
答案 3 :(得分:0)
替换
insert into #t Select count(*) from @Namee where isactive=0
带
exec ('insert into #t Select count(*) from ' + @Namee + ' where isactive=0')