检索数据库的空表

原理:
  就是拼接一段可执行的Sql 并存放进数据表中 表名可自定义
  该Sql返回空表(没有数据的表)的表名
  最后采用游标逐语句执行这些Sql

拼接查询Sql(查询sys.objects(数据库表对象)sys.columns(数据库列对象)两张表)并存入表中

select ('if (select count(1) from ['+o.[name]+'] ) = 0 select ''' + o.[name] + ''' tabname' + CHAR(10) ) as value into fa
from sys.columns c join sys.objects o on c.[object_id] = o.[object_id]
where (max_length>=4 or max_length=-1) and system_type_id in (35, 99, 168, 175, 231, 239, 241)
 
  --表示对象类型为表
    and o.[type]='U' and o.name<> 'fa' 
    --自定义条件
    and o.[name] not like '0_%'
 

--创建游标
declare aaa cursor for 
    select value from fa
 
  --为执行游标做准备
    --@sql接收存入表中的可执行语句
    declare @sql nvarchar(max)
  declare @num int 
    declare @num2 int 

    --总行数
    set @num2 = (select COUNT(1) from fa)
  --初始位置
    set @num = 0

    --打开游标
    open aaa
    --开始循环
      while @num<@num2
         begin 
               --取出值赋给@sql
               fetch next from aaa into @sql
               --执行Sql
               exec(@sql)
        set @num=@num+1 
          end

--关闭游标
close aaa
--删除游标
deallocate aaa
--删除表
drop table fa

 

 

posted @ 2022-03-23 09:17  殇琉璃  阅读(308)  评论(0编辑  收藏  举报