Help us understand the problem. What is going on with this article?

[SQLServer]入れ子のカーソルを使って、件数が1件以上のテーブル名一覧を作る

More than 1 year has passed since last update.

やりたいこと

レコードの件数が1件以上存在するテーブル名の一覧が作りたい。

やっていること

対象にしたいテーブル名の一覧を作成して、その中の件数が1以上の場合に出力
※呼び出し側でログなどに出力してしまえば、リストが作れる

DECLARE @table_name NVARCHAR(128);
DECLARE @rec_count int;

DECLARE CUR_TABLE CURSOR FOR
    select name from sys.tables where name like 'T\_%' ESCAPE '\'
    union all
    select name from sys.tables where name like 'D\_%' ESCAPE '\' 
    union all
    select name from sys.tables where name like 'M\_%' ESCAPE '\'
    union all
    select name from sys.tables where 
        name not like 'TMP\_%' ESCAPE '\' and
        name not like 'TT\_%' ESCAPE '\' and
        name not like 'PT\_%' ESCAPE '\' and
        name not like 'W\_%' ESCAPE '\' and
        name not like 'T\_%' ESCAPE '\' and
        name not like 'D\_%' ESCAPE '\' and
        name not like 'M\_%' ESCAPE '\' and
        name not like 'I\_%' ESCAPE '\' and
        name not like 'G\_%' ESCAPE '\' and
        name not like 'Z\_%' ESCAPE '\' ;

OPEN CUR_TABLE;

FETCH NEXT FROM CUR_TABLE INTO @table_name;

WHILE @@FETCH_STATUS = 0
BEGIN
    EXEC('DECLARE cr2 CURSOR FOR select count(*) from ' + @table_name)
    OPEN cr2
    FETCH NEXT FROM cr2 INTO @rec_count 
    CLOSE cr2
    DEALLOCATE cr2

    if @rec_count  > 0 PRINT @table_name

    FETCH NEXT FROM CUR_TABLE INTO @table_name;
END
CLOSE CUR_TABLE;
DEALLOCATE CUR_TABLE;

件数をどうやって取得して判定すりゃいいんじゃいと悩んだ。

<参考>
https://ameblo.jp/g-pinchan-new/entry-11496798995.html
https://www.atmarkit.co.jp/ait/articles/0209/03/news001.html

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした