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執行結果

轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/7401.html
標籤:SQL Server
