一个查询数据库所有表的存储过程(允许按表名模糊查询一级按显示数量进行分页)...

    这个东西呢也算是突发奇想,有一次要查看一个项目的数据库内容,但是数据库表实在太多了,逐个查看太费劲了,就想写个语句查询,但是发现很不好弄,就决定写个存储过程,本人以前也没有怎么写过存储过程,这个算是第一次写这么独立的存储了,有那里写的不好还望各位大大多多指点...谢谢各位大大了~

切入正题,下面是我写的存储过程,内容中每条语句做什么都已经标识上了注释:

 

 

代码
 
   
-- 判断是否存在存储过程
if exists ( select * from sysobjects where [ name ] = ' pro_selectTableAll ' )
begin
drop procedure pro_selectTableAll
end
go
-- 创建存储过程 名称为:pro_selectTableAll
create procedure pro_selectTableAll
(
-- 由于在sql编辑器中只能显示100条信息,每次输出多少张表 默认100
@showCount int = 100 ,
-- 查询条件 表头包含什么 默认空 查询全部
@name_like varchar ( 50 ) = '' ,
-- 可以由用户自定义第几页
@pageIndex int = 1
)
as
begin
-- 过程开始,设置不显示影响行数
set nocount on
-- 创建标量,用于存储共有多少表
declare @tableCount int
-- 循环显示第多少条数据,也是用来循环判断用的,同时也是座位临时标的id使用
declare @index int
-- 给其赋值
set @index = 1
-- 获得共有多少表数据
select @tableCount = count ( * ) from sysobjects where [ name ] like ( @name_like + ' % ' )
-- 查看是否存在虚拟表,如果有则删除
if exists ( select * from tempdb..sysobjects where id = object_id ( ' tempdb..#table1 ' ))
begin
drop table #table1
end
-- 外面输入的第一页,我们要减一,原因是第一次必须是从0开始,not in 查询的时候第一次要是总数乘以0 如:10*0 ,实现从0开始查询
if ( @pageIndex <> 0 )
begin
set @pageIndex = @pageIndex - 1
end
-- 查询出所有表名存在临时表中
select identity ( int , 1 , 1 ) as id , [ name ] into #table1 from ( select top ( @showCount ) [ name ] from sysobjects where [ name ] like ( @name_like + ' % ' ) and id not in ( select top ( @showCount * @pageIndex ) [ id ] from sysobjects where [ name ] like ( @name_like + ' % ' ) order by [ name ] ) order by [ name ] ) as abc
-- 循环打印,冲第一条开始条件是小于等于总条数就循环
while @index <= @tableCount
begin
-- 判断如果小于100条就打印,
if @index <= @showCount
begin
-- 创建参数存储表名
declare @tableName varchar ( 200 )
-- 循环获得表名
select @tableName = [ name ] from #table1 where id = @index
-- 输出当前第多少张表和表名
print ' 第“ ' + convert ( varchar ( 20 ), @index ) + ' ”张表的数据,表名为: ' + @tableName
-- 查询该表全部信息
execute ( ' select * from ' + @tableName )
set @index = @index + 1
end
else
begin
print ' 结束循环 '
-- 结束循环
break ;
end
end
-- 最后展示一下输出的指定数量的表以便和咱自己查询结果比较
select * from #table1
-- 存储过程结束
end
go

 

 

 

 

因为数据过多,sql server 2005的显示结果窗口会提示无法显示更多查出来的表,最多显示100个,没有办法,我就又给这个存储过程中添加上了一个翻页的功能,所以将他设立了3个参数,每页显示表数量、按表名开头模糊查询、当且页数。

以上是生成存储过程的代码,下面是进行测试:

代码
 
   
-- 第几页
--
执行存储过程 ↓
execute pro_selectTableAll 10 , ' tb_ ' , 2
/* ↑ ↑
每页显示数几条 ↑

表头,模糊查询条件
*/
-- 查询信息进行比较
select top 100 * from sysobjects where [ name ] like ( ' tb_% ' ) order by [ name ]

 

 

 呵呵..有什么写的不好的地方希望大家多多提点,谢谢大家

转载于:https://www.cnblogs.com/bq-blog/archive/2010/04/23/sql-proc_1.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值