本文主要介紹了一個獲得當前數據庫對象依賴關係的實用算法,具體示例請大家參考下文:
以下爲引用的內容:
create function udf_GenLevelPath()
returns @v_Result table (LevelPath int,OName sysname)
/****************************************************************/
/* 功能描述:按照依賴關係,列出數據庫對象 */
/* 輸入參數:無 */
/* 輸出參數:按照依賴關係排列的數據庫對象表,無依賴在前 */
/* 編寫: anna*/
/* 時間:2007-12-12 */
/****************************************************************/
as
begin
declare @vt_ObjDepPath table (LevelPath int,OName sysname null)
declare @vt_Temp1 table (OName sysname null)
declare @vt_Temp2 table (OName sysname null)
--依賴的級別,值越小依賴性越強
declare @vi_LevelPath int
set @vi_LevelPath = 1
--得到所有對象,不包括系統對象
insert into @vt_ObjDepPath(LevelPath,OName)
select @vi_LevelPath,o.name
from sysobjects o
where xtype not in ('S','X')
--得到依賴對象的名稱
insert into @vt_Temp1(OName)
select distinct object_name(sysdepends.depid)
from sysdepends,@vt_ObjDepPath p
where sysdepends.id <> sysdepends.depid
and p.OName = object_name(sysdepends.id)
--循環處理:由對象而得到其依賴對象
while (select count(*) from @vt_Temp1) > 0
begin
set @vi_LevelPath = @vi_LevelPath + 1
update @vt_ObjDepPath
set LevelPath = @vi_LevelPath
where OName in (select OName from @vt_Temp1)
and LevelPath = @vi_LevelPath - 1
delete from @vt_Temp2
insert into @vt_Temp2
select * from @vt_Temp1
delete from @vt_Temp1
insert into @vt_Temp1(OName)
select distinct object_name(sysdepends.depid)
from sysdepends,@vt_Temp2 t2
where t2.OName = object_name(sysdepends.id)
and sysdepends.id <> sysdepends.depid
end
select @vi_LevelPath = max(LevelPath) from @vt_ObjDepPath
--修改沒有依賴對象的對象級別爲最大
update @vt_ObjDepPath
set LevelPath = @vi_LevelPath + 1
where OName not in (select distinct
object_name(sysdepends.id) from sysdepends)
and LevelPath = 1
insert into @v_Result
select * from @vt_ObjDepPath order by LevelPath desc
return
end
go
--調用方法
select * from dbo.udf_GenLevelPath()
go
本篇文章來源於 理想中國|www.LixiangZg.com 原文鏈接:http://www.lixiangzg.com/zzedu/MSSQL/200901/48293.html