欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

sql server實現(xiàn)在多個數(shù)據(jù)庫間快速查詢某個表信息的方法

 更新時間:2017年03月13日 11:53:52   作者:繼續(xù)去踢波  
這篇文章主要介紹了sql server實現(xiàn)在多個數(shù)據(jù)庫間快速查詢某個表信息的方法,結(jié)合實例形式分析了SQL Server多個數(shù)據(jù)庫查詢的相關操作技巧,代碼備有詳盡的注釋,需要的朋友可以參考下

本文實例講述了sql server實現(xiàn)在多個數(shù)據(jù)庫間快速查詢某個表信息的方法。分享給大家供大家參考,具體如下:

最近出來實習,所在公司的服務器有十幾個數(shù)據(jù)庫,為了方便根據(jù)某個數(shù)據(jù)表的  表名  快速找到對應的數(shù)據(jù)庫,又復習了一下游標的知識,寫了下面這個sql代碼,方便自己的工作。

1.先了解一下系統(tǒng)存儲過程和系統(tǒng)表的使用,簡單介紹一下我用到的幾個系統(tǒng)存儲過程(資料參考網(wǎng)絡)

use master --切換到系統(tǒng)數(shù)據(jù)庫,因為下面用到的系統(tǒng)存儲過程和系統(tǒng)表大部分存在于該數(shù)據(jù)庫
go
exec sp_helpdb --查詢 當前 服務器的所有數(shù)據(jù)庫
select [name] from [sysdatabases] --查詢 當前 服務器的所有數(shù)據(jù)庫
select * from sysobjects where type = 'u'--列出 當前 數(shù)據(jù)庫里所有的表名
select * from information_schema.tables --列出 當前 數(shù)據(jù)庫里所有的表名(執(zhí)行對比一下與上面這個語句的查詢結(jié)果)
select * from syscolumns where id = object_id('spt_fallback_db') --列出指定表里的所有的信息,包括字段等等(根據(jù)需要修改參數(shù))

2.直接上代碼(具體請參考注釋,純屬學習,有錯請指出)

use master --切換到系統(tǒng)數(shù)據(jù)庫,因為下面用到的  系統(tǒng)存儲過程和系統(tǒng)表  大部分存在于該數(shù)據(jù)庫
go
------------------在當前服務器  根據(jù)表的名字  在多個數(shù)據(jù)庫進行查詢  得到哪個數(shù)據(jù)庫存在該表的信息------------------
declare @DataBaseName nvarchar(max) --定義變量(數(shù)據(jù)庫的名字)
declare cur cursor for select [name] from [sysdatabases] --定義游標,該游標指向  當前  服務器上的所有數(shù)據(jù)庫名字列表
open cur --打開游標
create table #TableInfo (table_catalog nvarchar(max),table_schema nvarchar(max),table_name nvarchar(max),table_type nvarchar(max)) --創(chuàng)建臨時表用于存儲所有數(shù)據(jù)庫的所有表信息
fetch next from cur into @DataBaseName --獲取游標的數(shù)據(jù),相當于獲取數(shù)據(jù)庫名字列表的第一條數(shù)據(jù)
while (@@fetch_status=0)
begin
print ''
print ''
print '當前數(shù)據(jù)庫: '+ @DataBaseName --讀出每個數(shù)據(jù)庫的名字
insert into #TableInfo --把存儲過程查詢出來的數(shù)據(jù)插進臨時表
exec('select table_catalog,table_schema,table_name,table_type from ' + @DataBaseName + '.information_schema.tables') --查詢對應數(shù)據(jù)庫的所有表
print '--------------------------------------------------------------------------------------------------------------------------------------'
fetch next from cur into @DataBaseName --游標移動
end
close cur --關閉游標
deallocate cur --釋放游標
print ''
print ''
print ''
print ''
print ''
declare @TableName nvarchar(max)
set @TableName = 'MyTableName' --查詢條件(根據(jù)需要自行修改)
if exists(select table_name from #TableInfo where table_name = @TableName) --查詢指定名字的表
begin
print '====================當前服務器存在 ' + @TableName + ' 表,相關信息請到結(jié)果窗口查看===================='
select table_catalog as '所屬數(shù)據(jù)庫',table_name as '表名' from #TableInfo where table_name = @TableName --輸出表的相關信息,從這些信息就可以知道這個表在哪個數(shù)據(jù)庫
end
else
begin
print '--------------------當前服務器不存在 ' + @TableName + ' 表--------------------'
end
drop table #TableInfo --刪除臨時表

更多關于SQL Server相關內(nèi)容感興趣的讀者可查看本站專題:《SQL Server查詢操作技巧大全》、《SQL Server存儲過程技巧大全》、《SQL Server索引操作技巧大全》、《SQL Server常用函數(shù)匯總》及《SQL Server日期與時間操作技巧總結(jié)

希望本文所述對大家SQL Server數(shù)據(jù)庫程序設計有所幫助。

相關文章

最新評論