Hierarchy Tree In Sql Server
May 15, 2008
Hai
do we have hierarchy query in sql like connect by prior in oracle to dispaly values in tree structure
Help needed
Tahnks in advance
Sumathi.s
Hai
do we have hierarchy query in sql like connect by prior in oracle to dispaly values in tree structure
Help needed
Tahnks in advance
Sumathi.s
ID ParentiD IsAutoCalculate Level
1 0 1 0
2 1 0 1
3 1 0 1
4 1 0 1
5 2 0 2
6 2 0 2
7 3 0 2
8 4 0 2
9 0 1 0
10 9 0 1
11 0 1 0
12 11 1 1
13 12 0 2
The above table shows a parent child relationship with the hierarchy shown in column level. for each parent (IDs 1, 9, 11), I want the first child level where the column IsAutoCalculate = 0
so for parent Id 1, the rows to be returned is of level 1 as that is the first child row of this parent with IsAutoCalculate = 0. The rows with level 2 should not be returned
For parent id 3, the rows to be returned will be with level 2 as this is the first child row of this parent with IsAutoCalculate = 0
I got assignment, how to make it appear in the right order .
/* DROP TABLE EMP
SELECT * INTO Emp FROM (
SELECT 'A' EmpID, NULL ManID, 'Name' EmpName UNION ALL
SELECT 'MAC' EmpID, 'A' ManID, 'Name__' EmpName UNION ALL
SELECT '1ABA' EmpID, 'MAC' ManID, 'Name____' EmpName UNION ALL
SELECT 'ABB' EmpID, '1ABA' ManID, 'Name______' EmpName UNION ALL
SELECT 'XB' EmpID, 'A' ManID, 'Name__' EmpName UNION ALL
SELECT 'BAC' EmpID, 'XB' ManID, 'Name____' EmpName ) b
*/
[code]....
Hello ,
I'm facing a complicated problem and I don't think that the solution will be an easy one.
I have an SQL statement in Oracle which I need to translate it in Sql Server 2005.
select lpad(' ',5*(orderid)) || to_char(descr) as menui
from <table _name>
where MENU_ITEM not in ('test1','test2','test3') and item_parent not in ('test4,'test5,'test6')
start with <item_parent='item_parent' >
connect by prior <menu_item = item_parent and menu_name='something'; > ?(condition)
Somewhere I have read that SQL server does not support Hierarchical Sql statements. Is this true ? How am I going to do that ?
Any help will be appreciated.
Thank you
Can anyone please help me? I need to create a tree structure of my company's database server. I need to include all the tables and their description in a tree structure. The output can be in any format. Is there some tool in the MSSql that will do this for me, so I don't have to write it out manualy?? Thank you very much for any ideas!!
M.
Hi,
Can we represent the Decision Tree in a programatically way in an .NET application? I understand that the outcome of a Decision Tree model can be integrated into an .NET application but not sure if we can also visualize it. Does MS SQL Server support any API to render such a tree?
Thanks a lot!
Dear fellows,
Can anybody tell me how can i apply recusive/Tree query using select
statement.
For example I've a table structure for an Organization as follows:
TableName: Employee_tbl
Fields: emp_id, emp_name, supervisor_id
emp_id emp_name supervisor_id
---------- --------------- -------------------
101 ZAFIAN
102 BRUNNER 101
108 CALLAHAN 102
105 RUSSO 102
110 SIM 102
103 DUELL 101
and so on
1. How can I get the above records in Hirarchical format starting from top
or from anywhere else in the hierarchy?
In Oracle it can be done as follows:
SELECT emp_id,emp_name,supervisor_id
FROM employee_tbl
CONNECT BY supervisor_id = PRIOR emp_id
START WITH supervisor_id is null;
Please reply me at the following address if possible:
faisal@visualsoft-inc.com
I'm working with a development bug database where if someone puts in a bug number, they want to get the parent bug. No problem.
SET @cur_parent = (SELECTdupeof_key
FROMqds.dbo.Dimduplicates d
WHEREd.dupe_key = @checkbug
ANDd.end_ts IS NULL)
WHILE @cur_parent IS NOT NULL
[Code] ...
However, now they want to be able to do the same thing in reverse. Put in a bug and determine how many bugs are duplicates (either directly - children, or indirectly - grandchildren/great-grandchildren, etc.).
The majority of bugs go no more than three generations deep but there are some that go much deeper so I need to have something where I can loop through each potential generation and get the number of bugs associated with it.
Example.
Parent Bug Child Grandchild GGChild
1 2 3 4
1 5
1 28 32
1 40 41 42
1 50
1 60
1 65 70
If I put in bug 1 I should be able to get a count of 13 associated duplicate bugs. Additionally, they want to be able to get a list of the bugs that are associated with that parent.
If there were a set number of levels, self-joining would work to create a generational matrix. However, as there is no limit on how deep the generations can go, I need something dynamic to traverse the tree and generate the list of bugs/count of bugs.
It was easy going up the tree because there was a strict one-to-one relationship between child and parent.
I am trying to traverse a tree structure like below,
1 Pets
--1.1 Cat
----1.1.1 Persian
----1.1.2 Bengal
--1.2 Dog
----1.2.1 Poodle
2 etc
I would like to be able to search by a keyword, i.e. Poodle, or the reference number, i.e. 1.2.1. I would prefer to do this all through a stored procedure if possible, it seems recursion is the way to go as the number of levels may increase in the future but i'm completely new to this. From what i've seen so far I would need a table structure with a parentID,NodeID,Name field and Primary key.
i.e,
ID...Name......Parent.....NodeID
1....Pets.........0............1
2....Cat..........1............1
3....Dog..........1............1
4....Persian.....2............1
5....Bengal......2............2
6....Poodle......3............1
etc
i've heard that SQL SERVER 2005 provides recursion through CTE, is this the recommended way/only way to achieve this?
Any tips on where to start would be really appreciated.
We need to present hierarchical data on a web page, the same way thetree view shows files in Windows Explorer. Here's the catch: thattree view needs to be bound to a SQL Server database. How can this bedone?
View 3 Replies View RelatedI want to get the employee hierarchy like tree structure and reportes.
View 7 Replies View RelatedI am trying to output the hierarchical data of a tree to xml format.
I can query the data from the tables into a friendly format like this:
create table dummy
(
id int,
childname nvarchar(max),
parentid int,
parentname nvarchar(max)
[Code] ....
And I always know the root ID from the first record on "table" dummy (generated with a common table expression), in this case it's ID 1, but from here, how to process this for any level of depth ?
hi,
How to get 2 level tree node in the sql server 2005. We have table with data.On load we populate the tree in Asp.net.
Regards,
Vinayak Panchal
Good day to all!I have a problem to resolve.Which is the script in sql in order to define one hierarchy of products categories?I have need to define the script for the creation of the table and store procedures (INSERT,DELETE,UPDATE,GET,GETALL).Thanks for the eventual answers !
View 2 Replies View RelatedI have a table named 'DepartmentItem' which is designed with hierarchy structure. The column 'ParentId' from table DepartmentItem indicates parent-child relationship and department root among records. I have written and run a user-defined function I use recursive approach, but the function runs slowly.
My question: is there a better way to query that hierarchy table instead of using recursive?
** The current user-defined function that is written using recursive:
CREATE FUNCTION dbo.fnGetDepartmentTree
(
@departmentItemId int
)
RETURNS TABLE
AS
RETURN
with DepartmentItemTree(DepartmentItemId , DepartmentItemTypeId , ParentId, ItemOrder, Level)
[code].....
** And definition of table 'DepartmentItem' :
DepartmentItemId int IDENTITY(1,1) NOT NULL,
ParentId int NULL, -- Each department root starts when this column is NULL or the current row is department root. If it is not NULL then the current row has ParentId whose record has DepartmentItemId = ParentId of the current row (see more below)
IsActive bit NOT NULL DEFAULT ((1)),
[Code] .....
I have a table "t_prod_cat" which contains hierarchical data which is used in production to present data.
CREATE TABLE [dbo].[t_prod_cat](
[cat_node_id] [bigint] IDENTITY(1,1) NOT NULL,
[advertiser_id] [bigint] NOT NULL,
[cat_hid] [hierarchyid] NULL,
[level] AS ([cat_hid].[GetLevel]()) PERSISTED,
CONSTRAINT [PK_t_prod_cat] PRIMARY KEY CLUSTERED
(
[cat_node_id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
In order not to impact the production website during the time an advertiser is editing (the editing might take much time and also mainly because at any time during the editing, the advertiser could cancel all the changes he did), I was thinking of transferring all the data linked to that advertiser to another table and let the advertiser apply any modifications up to the moment he will commit the changes.
Therefore, I would like to "CLONE" the hierarchy related to a certain advertiser_id to another table "t_prod_cat_work"
CREATE TABLE [dbo].[t_prod_cat_work](
[temp_cat_node_id] [bigint] NOT NULL,
[temp_cat_hid] [hierarchyid] NOT NULL,
[advertiser_id] [bigint] NOT NULL
) ON [PRIMARY]
What can be the easiest way to clone all the hierarchical data (multi-levels) from 't_prod_cat' to 't_prod_cat_work' for a certain advertiser_id ?
HiI'm trying to convert some verbose SQL Server 2000 T-SQL code that useslots temp tables and the like into a SQL Server 2005 only version,possibly using CTE.What I want to achieve is a menu like that onhttp://www.cancerline.com/cancerlin...9801_6_3_3.aspxNotice how you have the top level menu items, and then child nodesexpanded down to the low level page that link sends you to.Table sql:CREATE TABLE [dbo].[NavigationNode]([NodeId] [int] primary key nonclustered,[Text] [nvarchar](150) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,[AlternativeText] [nvarchar](250) COLLATE SQL_Latin1_General_CP1_CI_ASNULL,[Level] [int] NULL,[ParentNodeId] [int] constraint fk_parent_navnodeforeign key references [NavigationNode] ([NodeId]))Table data:1HomeNULL1NULL2SolutionsNULL113Solutions child1NULL224Solutions child2NULL225ContactNULL116solutions child1 child1NULL337solutions child1 child2NULL338solutions child1 child3NULL339solutions child1 child4NULL3310contact child1NULL25I have started to write some code with the common table expressionsyntax:declare @root int;set @root = 2;WITH Nav([NodeId],[ParentNodeId], [Text], [Level]) AS(SELECT [NodeId], [ParentNodeId], [Text], [Level]FROM [dbo].[NavigationNode]WHERE [ParentNodeId] = @rootUNION ALLSELECT n1.[NodeId], n1.[ParentNodeId], n1.[Text], n1.[Level]FROM [dbo].[NavigationNode] n1INNER JOIN Nav n2ON n1.[ParentNodeId] = n2.[NodeId])SELECT *FROM NavWhich returns:32Solutions child1242Solutions child2263solutions child1 child1373solutions child1 child2383solutions child1 child3393solutions child1 child43However I would prefer to the childnode, and then get parents of thatchild recursively. Doing that would leave me with a result set thatcould add the top level menu items to and have all the data required.Any help is greatly appreciated.-Brian
View 1 Replies View RelatedI have a tree and I need to copy a nested sub-tree (an element with its children, which in turn may have their owns) from one place to another.
The system should allow to handle up to 8 levels. I do know how to move, but cannot figure out how to copy.
Below is a working example With Create Table, Select and Cut / Paste (implemented via Update).
I would like to know how to copy a nested tree with reference id 4451 from Parent_Id 1 to Parent_Id = 2
--***** Table Definition With Insert Into to provide some basic data ****
IF (OBJECT_ID ('myRefTable', 'U') IS NOT NULL)
DROP TABLE myRefTable;
GO
CREATE TABLE myRefTable
(
Reference_Id INT DEFAULT 0 NOT NULL CONSTRAINT myRefTable_PK PRIMARY KEY,
[Code] ....
How to Copy nested sub-tree 4451 with all its children to Parent_Id 2, without deleting from Parent_Id = 1 ?
Dear All,
I have a dataminig programming that need to run for days. Is it possibile to speed up the training process by clustering several server by Windows 2003 clustering services? Is it actually that clustering 2 QUAD core computer is almost giving comparable performance as the sum of the speed of two (There must be some overhead, I know). I am actually familiary with the use of clustering. Is it just for making the server farm more reliable or it will collaborate and speeed up the whole training process?
If it is, is there any limit on the number of cluster is in the cluster. What version of Windows and SQL Server do I need to achieve speed up of data mining training process?
Thanks and regards
Tony Chun Tung Siu
Dear All
The problem is I am going to predict the production for different category of product.
attributes are
year - key
A production - predict only
B production -predict only
C production -predict only
And in the SQL it is impossible to to give input and predict (I am not sure whether that is a error or not).
And in the decision tree
for the
Product A - get as product A >=12324
Product B year > 2000
Product C product C >=35454
I want to know why the label is changing time to time.
Please help me on this. Thank you
Menik
I have been trying to convert an existing table that used adjacency list model (parentid,childid) to a table that use hierarchy Id type. So early on, I notice my original data does contains multiple roots. So I took a step to create dummy nodes to ensure all nodes fall into a single root structure. Another important fact is that each child node can have multiple parents.
My original source table contains 22461 records, when running the query below step 2 produces explosive number of records around 175,000+ records. I spent hours study the result and couldn't understand what actually causing this, I ran it against small set of test data I didn't seem the issue caused by child with multiple parents.
select * from SourceTable -- produces 22461 records
--step 1: first, get row number of child records in each parent
SELECT ChildID,ParentID, ROW_NUMBER() OVER (PARTITION BY PARENTID ORDER BY PARENTID) as Num
INTO #RelationshipTmp
FROM SourceTable;
[Code] ....
I've got a fairly large hierarchy table and I'm trying to put together a query to find the lowest level descendants of the hierarchy. I think there must be some way to use the "Breadth-first" approach that's stated in the MSDN technet sites about SQL Server HierarchyID but i'm not sure how to write the necessary T-SQL to traverse that. I know I can get all the descendants of a parent node like this
SELECT *
FROM AdventureWorks2012.HumanResources.Employee
WHERE OrganizationNode.IsDescendantOf(@ParentNode) = 1
However, this query returns all levels for that parent's branch. If I just wanted list of employees that were at the lowest level of the branch(es) for this parent node, how would I do this?
I am working on a query to generate parent child hierarchy from a table.
Table has below records.
--===== If the test table already exists, drop it
IF OBJECT_ID('TempDB..#mytable','U') IS NOT NULL
DROP TABLE #mytable
--===== Create the test table with
CREATE TABLE #mytable
[Code] ...
how to achieve this.l tried with temp tables it doesn't work.
Dear all,
I would like to know how to create a single level hierachy structure in SQL.
Example, I have a single parent record in table A that may later on spawn one or child record in table B that relates back to the parent. It only needs a single level.
that means, one to many.
thanks and rgds.
Loke HC
I have two tables.
table1 has 3 fields a , b and c. field "a" is a primary key.
table2 has 2 fields x and y. Fields x and y are nothing but the value of "a". Also, y is the child of x.
Therefore, x and y can never have same value. It means value of "a" either be child or parent.
But there is possibility that parent has no child.
Now, i wanted to write Select/Insert query for parent, b , c and child.
This tree is no a binary tree but N-Ary Tree.
Thanks,
sha
HI!
I am new in DB so I need some advices for finding the right solution.
I need to be able to make automatically any join between tables which the user choose and deliver the result.
is like making an hierarchy between all tables in DB (parent-child) and then making the select statement for the right join.
if u have any idea about how can I manage this, pls help me.
thanks a lot!
I have an Interesting situation that I'm hoping some of you experts can help me with basically I have the following hierarchy:
Net Profit
.....Gross Profit
..........Revenue
..........Direct Costs
.....Indirect Expense
Now, I have another hierarchy - separate from the above - that I need to assimilate to the hierarchy above - Example:
Expenses
.....Node a
..........Child a (Indirect Expense Type)
.....Child b (Direct Cost type)
Net Sales Adjustments
.....Child a (Revenue type)
.....Child b (Revenue type)
Depending on the type, the top most node needs to be assigned to the appropriate node in the initial hierarcy, like this:
Net Profit
....Gross Profit
........Revenue
................Net Sales Adjustments
....................Child a (Revenue type)
....................Child b (Revenue type)
........Direct Costs
...........Expenses
.................Child b (Direct Cost type)
........Indirect Expense
............Expenses
.................Node a
.....................Child a (Indirect Expense Type)
Now, I've been able to figure out how to assign the top most node and leafs if all the children have the same type (using the expan stored proc listed in the books online), but my question is on this portion:
Expenses
.....Node a
...........Child a (Indirect Expense Type)
.....Child b (Direct Cost type)
Basically, the answer is to work backwards - if a child has a type that is different than the other children, a copy of the hierarch (up to the child) needs to be made and assigned to the appropriate initial node.
I've tried modifying the expand stored proc to give me the lineage of the child and see if there's a way I can copy the node and place it appropriately - I'm brainfried at this point, and I'm hoping that someone outthere can point me in the right direction.
Thanks in advance for your time
Hai everyone.,
i need to get solution for tree hierarchy in sql is there any solution or any keyword like 'connect by prior' in oracle ..
plz help me on this..
for example:
id | FName |parentid |
1 | sandy |
2 | robert| 1
if i give the parentid 1 in where condition of a query i need the details of 'sandy'
Thanks in Advance.
B.Arul.
Hello!I have a table that looks like this:Col1; Col2; Col3; Col4; Col538; 75; 233; 916; 277038; 75; 233; 916; 277138; 75; 233; 916; 277238; 75; 233; 923; 265438; 75; 233; 923; 265538; 75; 245; 913; 245438; 75; 245; 913; 2456....And I need a query (not a procedure) that shows me this:38; NULL; NULL; NULL; NULLNULL; 75; NULL; NULL; NULLNULL; NULL; 233; NULL; NULLNULL; NULL; NULL; 916; NULLNULL; NULL; NULL; NULL; 2770NULL; NULL; NULL; NULL; 2771NULL; NULL; NULL; NULL; 2772NULL; NULL; NULL; 923; NULLNULL; NULL; NULL; NULL; 2654NULL; NULL; NULL; NULL; 2655NULL; NULL; 245; NULL; NULLNULL; NULL; NULL; 913; NULLNULL; NULL; NULL; NULL; 2454NULL; NULL; NULL; NULL; 2456....Does anybody know how i can get this result? How?Help! Thank you!SQLNullps: SQL-Server 2000
View 3 Replies View RelatedHi to All!
Is there a perfect method to implement a hierarchy structure with different types as a table in Sql server 2005? Currently I am thinking of this way:
[Node | ParentId | ParentType | ChildId | ChildType]
But there is this nagging little voice saying it can be better
Cheers!
Nele
Hi,
I'm having a major brain-failure moment here.
Using T-SQL I want to be able to get all of the leaf nodes (e.g. nodes at the furthest end of a tree from the root) in a hierarchical relationship where the table structure is such NodeID|ParentID|NodeName.
Basically if I had the following tree structure:
Root
Child1
Grandchild1
Child2
Grandchild2
I want to get all of the Grandchild nodes. Number of levels will vary and I haven't got any kind of HasChilds column.
I know this is possible because I remember having done it on a course years ago but I can't for the life of me figure it out on this sunny Friday afternoon. I know it's going to involve either recursion, a while loop or cursors but my mind is currently jelly. Can anyone help?
hi. I am working on Multiline Marketing Project.I have to calculate all the childens and display the whole tree..I have save records in tree format...But not able to calculate the all childrens.
SELECT count(*) FROM dfTree WHERE id in (SELECT id FROM dfTree WHERE lineage like '16%')
This query works properly.Problem is that it is not working in the project because in the like I have to pass a variable.
SELECT count(*) FROM dfTree WHERE id in (SELECT id FROM dfTree WHERE lineage like '@idl%')
Please Suggest me...
HI,
I am working on a Family tree portal which need tree functionality to display family members in tree structure. on click on any node the adding option should be displayed
for this i need a table and procedure to complete family tree
Thanks
@mbi