码迷,mamicode.com
首页 > 数据库 > 详细

SQLServer之查询当前服务器下所有目录视图表

时间:2020-02-25 13:17:29      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:cut   dealloc   服务器   database   tran   sele   技术   com   name   

SQL脚本

/*************1:删除临时表*************/
if exists(select * from tempdb..sysobjects where id=object_id(‘tempdb..#tempTable‘))
	drop table #tempTable;

/*************2:定义游标*************/
declare databaseNameCursor cursor for select name from master.dbo.SysDatabases;
declare @databaseName nvarchar(512),@databaseCount int;
set @databaseCount=(select count(1) from master.dbo.SysDatabases);

/*************3:打开游标*************/
open databaseNameCursor;

/*************4:连接游标*************/
fetch next from databaseNameCursor into @databaseName

/*************5:创建临时表*************/
create table #tempTable
(
id int identity(1,1) not null,
databasename nvarchar(max),
schemaname nvarchar(max),
tablename nvarchar(max),
primary key(id)
);

/************6:循环插入临时表中*************/
while (@@fetch_status=0 and @databaseCount>0)
	begin 
	    begin try
			set @databaseCount=@databaseCount-1;

			declare @tableFullName nvarchar(1024);
			set @tableFullName=‘select ‘‘‘+@databaseName+‘‘‘,schema_name(schema_id),name from ‘+@databaseName+‘.sys.tables‘;

			insert into #tempTable(databasename,schemaname,tablename)
			exec sp_executesql  @tableFullName;
			--指向下一个游标
			fetch next from databaseNameCursor into @databaseName  

		end  try
		begin catch
			continue;
		end catch
	end

/*************7:关闭游标*************/
close databaseNameCursor;

/*************8:释放游标*************/
deallocate databaseNameCursor;

/*************9:查看服务器所有表*************/
select * from #tempTable 

  

SQL脚本使用

先执行注释1,然后注释2到注释8脚本一起执行,最后执行注释9或者使用临时表。

SQL执行结果

技术图片

 

 

 

SQLServer之查询当前服务器下所有目录视图表

标签:cut   dealloc   服务器   database   tran   sele   技术   com   name   

原文地址:https://www.cnblogs.com/vuenote/p/12361020.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!