计算树路径的存储过程

时间:2016-02-04 11:12:45

标签: sql-server stored-procedures tree

我是SQL编程世界的新手,但我必须执行此过程。

用户给我一个存储树的主键,一个起始顶点和结束顶点。我计算这两个顶点之间的路径并返回结果,如列表:attribute1 =“value”,attribute2 =“value”......

假设是,用户必须给出一个在树的同一子分支中的路径,实际上我不检查这个错误的可能性。安全性不是要求,而是性能。出于这个原因,我问你关于我实施这个程序的专家意见。

DB以这种方式制作:

Tree(pk, ....); vertex(pk,parent,...,fk_tree); attr_def (pk, name);
attr_usage(pk, fk_vert, fk_attr, value, next);

我知道还有其他更好的数据库实现,但我也有时间限制,所以我认为这个解决方案很快就可以实现。

现在,如果您查看表格,您会注意到不同树中的顶点之间存在变量属性,但同一树中的节点具有相同数量的节点。所以我想用列表“a_usage.next”来滑动像列表这样的属性数量。

在这个函数中,我将总结我在路径中遇到的顶点的所有属性。我从完成顶点开始到通过父列的起始顶点。

在这些前提下,您是否有一些建议,以便找到一些错误并使我的存储过程更快?

这是我的代码:

    CREATE PROCEDURE [dbo].[calc_path]
    @tree_pk int, 
    @vertexa int,
    @vertexb int,
    @result nvarchar(255) OUTPUT

AS 
BEGIN

    declare @na int
    declare @sp int
    declare @ind int = 1

    select @na=T.natt, @sp=T.split from [dbo].Tree as T where T.id_tree=@tree_pk
    --nella tabella result tengo traccia per ogni attributi i valori sommati quando esco dal ciclo
    --con un cursore riesco li concateno in una stringa
    create table #result
    (
        attr_id int not null,
        attr_name varchar(10) not null,     
    )

     insert into #result(attr_id, attr_name)
         (select attrdef.id_attr, attrdef.name from attrdef)

    alter table #result add value int default 0

     --lavoro solo sui vertici dui quel determinato albero
    declare @cmd nvarchar (max)
    set @cmd = N'create view vert_tree
    as
    select * from vertex where vertex.tree_id ='+@tree_pk
    exec (@cmd)

declare @at int
declare @parent int
declare @t_value int
declare @t_value2 int
declare @t_next int
declare @t_attr int

while @vertexa = @vertexb
BEGIN
    --seleziono il vertice b dalla vista precedentemente creata
    select @parent = vert_tree.par, @at = vert_tree.attr from vert_tree where vert_tree.vertex_id = @vertexb
    --scorro la lista dei attributi
    while @na = @ind
    begin
    --ricerco l'attributo i-esimo del vertex b
        select @t_value = a_usage.value, @t_next = a_usage.next, @t_attr = a_usage.n_att
                 from a_usage where a_usage.attr = @at and a_usage.vertex = @vertexb
        --imposto il prossimo attributo
        set @at = @t_next
        --prendo il campo value dell'attributo specifico e lo sommo con quello corrente
        select @t_value2 = @result.value from #result where #result.attr_id = @t_attr
        set @t_value2 += @t_value
        --Rimetto il valore modificato nella tabella
        update #result set #result.value = @t_value2 where #result.attr_id = @t_attr
        set @ind += 1
    end
    set @ind = 1
    SET @vertexb = @parent
END
--Return the results from culcalating path
DECLARE @app nvarchar(max)
DECLARE cur CURSOR FOR SELECT attr_name, value FROM #result

OPEN cur
FETCH NEXT From cure INTO @app
while @@FETCH_STATUS = 0
BEGIN
SET @result += @app+', '
FETCH NEXT FROM cur INTO @app
END
CLOSE cur
drop table #result
RETURN @result
END
GO

感谢您的帮助!

0 个答案:

没有答案