2010-09-21 34 views
2

我已經聲明瞭一個Cursor來根據列名得到表名和列中的列號。請發現下面的查詢表名沒有被插入。請建議SQL Query根據列名得到表名和行數「

Create table #t 
(
tabname varchar(500), 
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 
--Print @Namee 
insert into #t(tabname) SELECT table_name FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME =' + @Namee + ' 
exec ('insert into #t(NoOfRows) Select count(*) from ' + @Namee + ' where isactive=0') 
Fetch Next From @Getname into @Namee 
End 
Close @GetName 
Deallocate @GetName 
select * from #t 

回答

2

您可以在一個INSERT插入行的表名和編號:

EXEC('INSERT INTO #t 
     (tabname, NoOfRows) 
     SELECT '''+ @Namee +''', COUNT(*) 
     FROM ' + @Namee + ' 
     WHERE isactive = 0') 

你有什麼使表的名稱和數量之間沒有聯繫,所以它不可能你錯過了一張表,但懷疑NoOfRows實際上與記錄中的表名。

+0

感謝OMG的工作。 – Simhadri 2010-09-21 17:25:28

0

您正在向臨時表中執行兩次插入,一次是爲表名稱(不計數),另一次爲沒有表名稱的計數。

見OMG小馬的SQL與替換你的,只是一個表名取出卡殼

1

這裏是一個更好的方式來獲得你想要的表(不會有目錄和架構重疊的一些問題)

declare @colname varchar(max) 
set @colname = 'isactive' 

SELECT table_name from information_schema.tables t 
    join information_schema.columns c on t.table_catalog = c.table_catalog and  
             t.table_schema = c.table_schema and 
             t.table_name = c.table_name and 
             column_name = @colname