用基于集合的查询替换游标

时间:2016-09-07 06:25:01

标签: sql-server cursor subquery

我想找到一组表的数量。表名是另一个表中的值。

- 像

      select count(*) from tablename

- tablename从

获得
      select tablename from table1

- table1有大约171个表名

我使用光标来获取每个表名并为每个表选择计数,但这需要时间。你能帮忙解决如何用基于集合的解决方案替换游标代码吗? 下面是我的光标代码

SET NOCOUNT ON;

if( OBJECT_ID('tempdb..#temptablenew') IS NOT NULL )
BEGIN
DROP table #temptablenew
END

select * into #temptablenew from table1

declare @srccount int
declare @tablename nvarchar(max);

declare @q2 nvarchar(max);

declare  @id int;

declare my_cursor cursor
local static read_only forward_only

for 

select id,tablename from #temptablenew 

open my_cursor
fetch next from my_cursor
into @id,@tablename
while @@fetch_status = 0
begin 



  set @q2 =N'select @srccount= count(*) from '+@tablename+' with (nolock)';

  execute sp_executesql @q2,@PARAMS = N'@srccount INT OUTPUT', 
      @srccount = @srccount OUTPUT

  select  @srccount,@id,@tablename

  fetch next from my_cursor
  into @id,@tablename
  end
  close my_cursor;
  deallocate my_cursor;

提前致谢

1 个答案:

答案 0 :(得分:0)

试试这个,

SET NOCOUNT ON;

declare @q2 nvarchar(max) = '';

SELECT @q2 = @q2 + 'SELECT COUNT(*) AS cnt, ''' + tablename  + ''' AS TableName FROM ' + tablename  + ' (NOLOCK); '  
FROM table1

--Print @q2
execute sp_executesql @q2