Skip to content

Instantly share code, notes, and snippets.

@ichiroku11
Created June 25, 2012 09:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ichiroku11/2987578 to your computer and use it in GitHub Desktop.
Save ichiroku11/2987578 to your computer and use it in GitHub Desktop.
全テーブルのレコード数を取得するクエリ
-- 結果を格納するテーブル変数
declare @result table(
Name sysname not null,
Rows int not null
);
-- テーブル名を取得するカーソル
declare cur cursor
for
select
sys.tables.name
from sys.tables
where sys.tables.type = 'U'
order by sys.tables.name;
declare @name sysname; -- テーブル名
open cur;
fetch next from cur into @name;
while @@fetch_status = 0
begin
-- レコード数を取得
declare @rows int;
declare @query nvarchar( max ) = N'select @p = count( * ) from ' + @name + ';';
execute sp_executesql @query, N'@p int output', @p = @rows output;
insert into @result values( @name, @rows );
fetch next from cur into @name;
end
close cur;
deallocate cur;
select *
from @result;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment