sql server - How to copy branch with hierarchyid? -



sql server - How to copy branch with hierarchyid? -

i have simple table fields:

catalog_id hierarchyid not null unique, item_id int not null identity(1,1), item_name nvarchar(50) not null,

i need create stored procedure re-create branch parent.

for example, this:

i've done procedure moving 1 branch 1 parent another, here is:

alter procedure [dbo].[move_child] @childid int, @newparentid int declare @nold hierarchyid, @nnew hierarchyid select @nold = catalog_id catalogstree item_id = @childid set transaction isolation level serializable begin transaction select @nnew = catalog_id catalogstree item_id = @newparentid select @nnew = @nnew.getdescendant(max(catalog_id), null) catalogstree catalog_id.getancestor(1)=@nnew ; update catalogstree set catalog_id = catalog_id.getreparentedvalue(@nold, @nnew) catalog_id.isdescendantof(@nold) = 1 ; commit transaction

but need create re-create same hierarchy , item_name.

i've made temporary table

alter procedure [dbo].[copy_child] @folder_id int, @new_parent_id int begin

create temporary table:

create table #temp_table( catalog_id hierarchyid not null unique, item_id int not null, item_name nvarchar(50) not null )

copy branch temporary table:

declare @folderid hierarchyid select @folderid = (select catalog_id catalogstree item_id = @folder_id) insert #temp_table (catalog_id, item_id, item_name) select catalog_id, item_id, item_name catalogstree catalog_id.isdescendantof(@folderid) = 1

change catalog_id:

declare @nold hierarchyid, @nnew hierarchyid select @nold = catalog_id catalogstree item_id = @folder_id set transaction isolation level serializable begin transaction select @nnew = catalog_id catalogstree item_id = @new_parent_id select @nnew = @nnew.getdescendant(max(catalog_id), null) catalogstree catalog_id.getancestor(1) = @nnew ; update #temp_table set catalog_id = catalog_id.getreparentedvalue(@nold, @nnew) catalog_id.isdescendantof(@nold) = 1 ; commit transaction

copy changed values main table:

insert catalogstree(catalog_id, item_name) select catalog_id, item_name #temp_table drop table #temp_table end

sql-server tsql hierarchyid

Comments

Popular posts from this blog

xslt - DocBook 5 to PDF transform failing with error: "fo:flow" is missing child elements. Required content model: marker* -

mediawiki - How do I insert tables inside infoboxes on Wikia pages? -

Local Service User Logged into Windows -