SQL Server 2012 :: Query To Generate Relationship (Parent Child Hierarchy From A Table)

Jul 18, 2015

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.

View 5 Replies


ADVERTISEMENT

SQL Server 2012 :: Query To Select Parent Details From Child Table

Mar 3, 2015

I have a scenario,

We have equipment table which stores Equipment_ID,Code,Parent_Id etc..for each Equipment_ID there is a Parent_Id. The PK is Equipment_ID Now i want to select the Code for the Parent_Id which also sits in the same table. All the Parent_Id's also are Equipment_ID's.

Equipment table looks like :

Equipment_ID Code DescriptionTreeLevelParent_Id
6132 S2611aaa 4 6130
11165 V2546bbb 3 1022
15211 PF_EUccc 5 15192
39539 VP266ddd 4 35200
5696 KA273eee 3 3215
39307 VM2611fff 4 35163
39398 IK264ggg 4 35177

There is another table for Equipment_Tree which has got Equipment_Tree_ID,Parent_Id and Equipment_ID does not has the Code here.

Select query where i need to select the Code for all Parent_Id's.

View 8 Replies View Related

How To Find Orphaned Value From Parent / Child Hierarchy Table

Aug 15, 2013

how to find the orphaned value from the below parent/child hierarchy Table.

create table dbo.Hier(parent varchar(100), child varchar(100))

insert into Hier
select 'subramanium','Manickam' union all
select 'subramanium','Munuswamy' union all
select 'Munuswamy','senthil' union all
select 'Munuswamy','sasi' union all
select 'Munuswamy','uma' union all
select 'manickam','vijay' union all
select 'manickam','bhavani' union all
select 'manickam','dhanam' union all
select 'uma','varsha'

Delete from Hier where child='uma'

I tried:

select parent from Hier
where parent not in(select Child from Hier)
and parent <> 'subramanium'
Getting resultset as:
parent
======
uma

I need to know whether my select statement is correct or not,if its correct,how to write the same in CTE?

View 2 Replies View Related

Using Same Table Having Parent And Child Relationship?

Mar 23, 2014

Below is my sample data of my table named "Groups"

Code:
with Groups as (
select 1 as GroupId,'Oracle' as GroupName,0 as IdParentGroup union all
select 2 as GroupId,'Microsoft' as GroupName,0 as IdParentGroup union all
select 3 as GroupId,'IBM' as GroupName,0 as IdParentGroup union all
select 4 as GroupId,'SunMicrosystem' as GroupName,1 as IdParentGroup union all
select 5 as GroupId,'peoplesoft' as GroupName,1 as IdParentGroup union all
select 6 as GroupId,'mysql' as GroupName,1 as IdParentGroup union all
select 7 as GroupId,'Nokia' as GroupName,2 as IdParentGroup union all
select 8 as GroupId,'EShop' as GroupName,2 as IdParentGroup union all
select 9 as GroupId,'Meiosys' as GroupName,3 as IdParentGroup union all
select 10 as GroupId,'UrbanCode' as GroupName,3 as IdParentGroup )
select * from groups;

Expected result:

Code:
with ExpectedResult as (
select 'Oracle' as GroupName,'SunMicrosystem' as SubGroup union all
select '' as GroupName,'peoplesoft' as SubGroup union all
select '' as GroupName,'mysql' as SubGroup union all
select 'Microsoft' as GroupName,'Nokia' as SubGroup union all
select '' as GroupName,'EShop' as SubGroup union all
select 'IBM' as GroupName,'Meiosys' as SubGroup union all
select '' as GroupName,'UrbanCode' as SubGroup )
select * from ExpectedResult;

some sample query to how to achieve this parent-child has the same table.

View 9 Replies View Related

T-SQL (SS2K8) :: Using Same Table Having Parent And Child Relationship

Mar 23, 2014

Below is my sample data of my table named "Groups"

with Groups as (
select 1 as GroupId,'Oracle' as GroupName,0 as IdParentGroup union all
select 2 as GroupId,'Microsoft' as GroupName,0 as IdParentGroup union all
select 3 as GroupId,'IBM' as GroupName,0 as IdParentGroup union all
select 4 as GroupId,'SunMicrosystem' as GroupName,1 as IdParentGroup union all

[Code] ....

Expected result:

with ExpectedResult as (
select 'Oracle' as GroupName,'SunMicrosystem' as SubGroup union all
select '' as GroupName,'peoplesoft' as SubGroup union all
select '' as GroupName,'mysql' as SubGroup union all

[Code] ....

How to achieve this parent-child has the same table.

View 5 Replies View Related

Hierarchy – Parent And Child

Aug 2, 2007

I am designing a table to represent data in hierarchy structure, I use id and parent id to represent the data in hierarchy form:

Id | parent_id
---+-----------
1 | 0
2 | 0
3 | 0
4 | 1
5 | 1
6 | 4
7 | 4
8 | 7
9 | 7


This structure requires complicated queries (recursive call) to find out all the child of a root node, so I have added another field for the root id.
Is this a good relational database design ? kindly suggest.

Id | parent_id | root_id
---+-----------+---------
1 | 0 |
2 | 0 |
3 | 0 |
4 | 1 | 1
5 | 1 | 1
6 | 4 | 1
7 | 4 | 1
8 | 7 | 1
9 | 7 | 1
10 | 2 | 2
11 | 2 | 2
12 | 10 | 2
13 | 10 | 2

Rgds
Vijay

View 3 Replies View Related

Parent-Child Hierarchy But Reversed(!)

Feb 21, 2007

Hi!

I have a report that uses a parent-child hierarchy in a table. It is hidden with the toggle set to itself, and that works perfectly.

However, instead of having it look like this(simple example):

+ Profit

After the + has been clicked:

-Profit
+Sales
+Cost

I would like it to look like this:

+Sales
+Cost
-Profit

Is this possible with when using a parent-child hierarchy?



http://ssasfreak.spaces.live.com/

View 2 Replies View Related

Flattening Parent Child Hierarchy: Urgent Please Help

Aug 10, 2006

Hi Expert,How do I flatten a Parent Child hierarchy to regular flat data: pleaseprovide some SQL code:I have now:Task_ID, Parent_Task_ID, Task_NameLevel11Project Management121Costing231Estimating242Task1352Task2363Task3373Task43I want to have:Level1Level2Level3Project ManagementCostingTask1Project ManagementCostingTask2Project ManagementEstimatingTask3Project ManagementEstimatingTask4Please help, I am stuck!Thanks in advance.Soumya

View 2 Replies View Related

How To Drill Down A Parent Child Hierarchy In Reporting Services 2005 ?

Sep 26, 2007



Hello,

I want to enable a drill down on a parent child hierarchy, just as it is possible in the Analysis Services.


An Example :



Hierarchy in a company : Jack (1) is the boss, Frank (2) and Andy (3) ar the Semi-Bosses , and Julia (4), Jane (5), Henry (6), Michael (7), Will (8) , Dave (9) are normal employees . Timmy(10) is a trainee. Furthermore Frank is responsible for Julia,Jane and Henry and Andy is responsible for Michael WIll and Dave. Dave is responsible for Timmy. So we get the following tree hierarchy structure.

1
2 3
4 5 6 7 8 9
10

My Employee Dimension Attributes : Name, Parent

I want to make a report, where I show the salary of each employee. But at first the user only sees 1, when he drills down he sees 2 and 3, too. When he drills down once more he sees 4 5 6 and 7 8 9, too (The user must be able to recognize which person is responsible for 456 and which for 789). And the last drill down shows 10, for which 9 is responsible ( exactly as it is possible in the analyis Service in the Cubebrowser)



I have read some posts where are MDX examples which are similar to my problem, but they did not solve my problem.


I hope somebody can help me


JF

View 6 Replies View Related

Parent-child Hierarchy In A SSRS Project Using A SSAS Datasource

May 4, 2007

Hi everybody,



I would like to know how to create a hierarchy in a SSAS project using a SSRS datasource?



All values are displayed when I drag the field "parent" in the MDX generator...



Thanks in advance for any idea...









View 1 Replies View Related

Parent | Child Relationship And Showing Tree

Aug 3, 1999

Hi!

I am new to SQL Server and am starting to learn. Here is an issue I have not solved yet:

If I have a table with an CompanyID, Parent ID, Child ID and CompanyName and given a CompanyID, how would I (using a stored procedure I imagine) provide a Tree Structure of the company and all it's descendants?

Also, how would I show it's ancestry?

Company1
subsidary1 > subsidary1's child
subsidary2 > it's children, etc...etc...

I hope I phrased the questions right.

Thanks for your help!
Scott

View 1 Replies View Related

Need To Insert Parent/child Relationship Rows Into DB

Oct 18, 2006

Hi

I need to read a file and write parent/child relationship rows. I cannot seem to fugure out how I can generate keys that I an use for the relationship.

I looked at using a variable, but have no joy - I cannot instantiate the variable and it errors - notsure wy.

I also looked to see if I can write to a DB table that maintains key id, but not sure how to do that.

I alo thought of setting up the parent table key to be auto-increment,but canot see how I can read this so that I can us it in the child row inserts.

Help will be really appriciated

Thanks in advance.

View 3 Replies View Related

Parent Child Relationship Column Hint?

Feb 22, 2007

I've got a dilemma which I hope someone has a solution to.

Let's say we're building a data mining model to predict aircraft reliability. In the training table we've got a column (among many others) with a unique aircraft ID, and then a column for the type (737,747) and then a column for the series (100,200,300). I.E. A 737-800 series would be "737" and "800".

There is in essence a parent-child relationship between these 2 columns. 737's should share a common set of reliability factors, and then those factors might be further defined by the series number (for instance, the 737 might have very reliable radar except for the 500 series). The series is analogous to what model year a car is. What I want to make sure doesn't happen is for the system to correlate a 747-400 and a 737-400 because they are the same series. They are totally independent if the model number is different.

My only idea was to merge the columns and have a single value "737-100". But it would seem then that the model won't have any idea that a "737-100" and "737-200" should have a lot more in common than a "737-100" because the values will be completely different.

I was hoping to find some sort of parent-child hint in the column properties but found none.

What solutions have other people tried? It sure seems that there should be an elegant solution for something like, but I'm missing it.

Geof

View 3 Replies View Related

SSIS And Parent-Child Relationship Tables

Jun 15, 2006

Supose I have two records in a parent-child relationsuip (actually I have many more such records). Does SSIS offer any support ask for inserting one record into the parent table, the other into the child table, and updating the foreign key of the child to point to the parent?

TIA,

Barkingdog

P.S. I have to do just this as part of the datawarehouse test I'm running. Seems like a common task but I don't recall anything in SSIS addressing the issue.







View 5 Replies View Related

SQL 2012 :: Build Tree From Child To Parent Table

Jan 15, 2015

I'm playing with CTE and just want to expand my skills and ask how you would build this tree structure to fill that [Tree] column for table like in sample below:

/* CREATE TABLE #T1 (child_id INT, parent_id INT, tree VARCHAR(MAX))

INSERT INTO #T1 VALUES
( 200,3, '200-3-2-1' ),
( 100 , 14 , '100-14-1'),
( 3 , 2 , '3-2-1'),
( 2 , 1 , '2-1'),
( 14 , 1 , '14-1'),
( 1 , NULL , '1');

[Code] .....

View 2 Replies View Related

Inserting Data Into Two Tables With Parent-child Relationship

Nov 13, 2006

I am trying to insert data into two tables with a SSIS package. One table has a foreign key relationship to the other table's primary key. When I try to run the package, the package will just seems to hang up in bids. I have found two ways around the issue but I don't like either approach. Is there a way to set which table gets insert first?

If I uncheck the check constraints option on the child table, the package will run very quickly but this option alters the child table and basically disables the constraint. I don't like this option because it is altering the database.

The second approach is to set the commit level on both tables to say 10,000 and make sure that the multicast component has the first output path moved to the parent table. I don't like this option because I am not sure if the records are backed out if the package should abend after records have been committed.

View 1 Replies View Related

Analysis :: Include And Exclude Children In A Single Hierarchy In Parent Child Dimension In MDX

Apr 8, 2015

Include children and exclude children in a single  hierarchy in parent child dimension in mdx

*12-parent
 **20-parent
 - 9-parent
       --250-child1
       --210-child2
        --240-child3
aggregation of 12-parent only
aggregation of 20-parent only
aggregation of  9 with children

View 3 Replies View Related

SQL Server 2012 :: Better Way To Query A Hierarchy Table?

Jan 21, 2015

I 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] .....

View 2 Replies View Related

SQL 2012 :: Group By Parent With One Child And Multiple Child Information?

Jul 25, 2014

Basically i have three Tables

Request ID Parent ID Account Name Addresss
1452 1254789 Wendy's Atlanta Georgia
1453 1254789 Wendy's Norcross Georgia
1456 1254789 Waffle House Atlanta Georgia

Bid_ID Bid_Type Bid_Volume Bid_V Bid_D Bid_E Request_ID Parent ID
45897 Incentive 10 N/A N/A N/A 1452 1254789
45898 Incentive 10 N/A N/A N/A 1453 1254789
45899 Incentive 10 N/A N/A N/A 1456 1254789

Bid_Number Bid_Name Request_ID Parent ID
Q789456 Wendy'Off 1452 1254789
Q789457 Wendy'Reba 1452 1254789
Q789456 Wendy'Off 1453 1254789
Q789457 Wendy'Reba 1453 1254789
Q789456 Wendy'Off 1456 1254789

I want the Result

Parent ID Bid_Type Bid_Volume Bid_V Bid_D Bid_E AutoGeneratedCol
1254789 Incentive 10 N/A N/A N/A 1
1254789 Incentive 10 N/A N/A N/A 2
Bid Number AutoGeneratedCol_Link
Q789456 1
Q789457 1
Q789456 2
Request ID AutoGeneratedCol_Link
1452 1
1453 1
1456 2

View 1 Replies View Related

SQL Server 2012 :: Create XML With Parent And Child Element

Jul 8, 2015

I want to create an XML file with the below format.

office_tel and mobile are fields of a table.

<fields>
<office_tel>
<value>1234</value>
</office_tel>
<mobile>
<value>99999</value>
</mobile>
</fields>

View 2 Replies View Related

Query Based Off Primary Key Of Parent Table - Adding Child Table

Jan 28, 2012

I need to add a child table that will tell us who the participants counselor is, what I did was I did a Make Table query based off the primary key of the Parent table and made that the link (foreign key) for the People_tbl and the Counselor_tbl, so if the counselor changes then the user adds the record to the counselor tbl and then puts in the Effective date. The problem is that when I run a report it doesn't show the present counselor always shows the old counselor?

Code:
SELECT Student_ind.StudentFirstName, Student_ind.StudentLastName, Student_ind.[Student ID], People_tbl.[Family ID], People_tbl.FirstName,
People_tbl.LastName, People_tbl.[Parent ID]
FROM People_tbl RIGHT OUTER JOIN
Student_ind ON People_tbl.[Family ID] = Student_ind.[Family ID]
WHERE (People_tbl.LastName = @Enter_LastName) AND (People_tbl.FirstName = @Enter_FirstName)

View 5 Replies View Related

SQL Server 2012 :: Statement To Group Rows As Multiple Child Under Single Parent?

Sep 18, 2014

I've 2 tables QuestionAnswers and ConditionalQuestions and fetching data from them using CTE join and I'm seeing repetitive rows (not duplicate) like, If you have multiple answers for 1 question, the output is like

where london
where paris
where toronto

why us
why japan
why indonesia

I want to eliminate the repetitive question and group them as parent child items.

with cte as (
select cq.ConditionalQuestionID from ConditionalQuestions cq
inner join QuestionAnswers qa on cq.QuestionID=qa.QuestionID where cq.QuestionID=5 and qa.IsConditional='Y')
select distinct q.Question, a.Answer from QuestionAnswers qa
inner join Answers a on a.AnswerID = qa.AnswerID
inner join Questions q on q.QuestionID = qa.QuestionID
inner join cte c on c.ConditionalQuestionID = qa.QuestionID;

View 4 Replies View Related

Transact SQL :: Parent / Child Tables - Pivot Child Data To Parent Row

May 19, 2015

Given the sample data and query below, I would like to know if it is possible to have the outcome be a single row, with the ChildTypeId, c.StartDate, c.EndDate being contained in the parent row.  So, the outcome I'm hoping for based on the data below for ParentId = 1 would be:

1 2015-01-01 2015-12-31 AA 2015-01-01 2015-03-31 BB 2016-01-01 2016-03-31 CC 2017-01-01 2017-03-31 DD 2017-01-01 2017-03-31

declare @parent table (Id int not null primary key, StartDate date, EndDate date)
declare @child table (Id int not null primary key, ParentId int not null, ChildTypeId char(2) not null, StartDate date, EndDate date)
insert @parent select 1, '1/1/2015', '12/31/2015'
insert @child select 1, 1, 'AA', '1/1/2015', '3/31/2015'

[Code] .....

View 6 Replies View Related

Trying To Enforce Ref Integrity On Hierarchy Table Relationship

Dec 28, 2007

I've got a table that includes:CREATE TABLE [dbo].[Content] (  [Id] int IDENTITY(1, 1) NOT NULL,  [ParentId] int NULL,
I'm wanting to make sure that a ParentId must be in the table as Id someplace else.  When I try to do it by making it a foreign key  get the error:
--------------- SQL ---------------
ALTER TABLE [dbo].[Content]ADD CONSTRAINT [Content_fk3] FOREIGN KEY ([Id])   REFERENCES [dbo].[Content] ([ParentId])   ON UPDATE NO ACTION  ON DELETE NO ACTIONGO
---------- ERROR MESSAGE ----------
There are no primary or candidate keys in the referenced table 'dbo.Content' that match the referencing column list in the foreign key 'Content_fk3'.Could not create constraint. See previous errors.
 
Any ideas? 
 
ALTER TABLE [dbo].[Content]ADD CONSTRAINT [Content_fk3] FOREIGN KEY ([Id])   REFERENCES [Content].[dbo] ([ParentId])   ON UPDATE NO ACTION  ON DELETE NO ACTIONGO
 

View 3 Replies View Related

SQL 2012 :: SSIS FTP Task - Can't Move From Child Folder To Parent

Jan 13, 2015

I have set up an FTP connection that tests successfully. I can log on to the FTP site with the same credentials and see my root folder, and within that, two more folders. In my FTP task, I want to receive files to my local machine. The problem is that the only remote path available is not at the root level, and the only thing I can see are files from one of the child folders, but not the child folder I want.

Is it possible in the remote path to change folders? The remote path just shows a "/", which I thought would be the root level, but it is somehow linked to a child folder.I've tried various combinations to get to the folder I want, /root folder/child folder, but that gives the error that the folder does not exist.

If I open the FTP Task Editor, click on File Transfer, and click the ellipses for the Remote Path, the Browse For File box opens, with a "/" in the Location section, and a list of files in the child folder that I do not want to be in. If I click the "Up Directory" button, I get the message "Already at top level directory".

how I can get the files from one particular folder on the FTP site?

View 0 Replies View Related

Query To Generate Hierarchy In Organization

Jun 8, 2014

I need to write a sql that generate the hierarchy in an organization.

Below an example

emplid empname supervisor_id superv_name
1 subu null null
2 vid 1 sub
3 ram 4 satis
4 satis 2 vid

I need an output to this query as below and also one important the supervisor ie supervisor_id and name is null is the top level,every employee also has to report to him and also to his all above supervisors.

Whoever joining new to org the hierarchy

empid empname supervisor_id superv_name
3 ram 4 satis
4 satis 2 vid
2 vid 1 subu
4 satis 1 subu
3 ram 1 subu
3 ram 2 vid
5 kumar 1 subu
5 kumar 4 satis
5 kumar 2 vid
1 subu null null

View 3 Replies View Related

Integration Services :: Pass Variables Parent To Child Packages In SSIS 2012

Aug 8, 2013

How to pass variable from Parent to child and child to Parent Packages  is this possible in SQL SSIS 2012. I need this only in SSIS 2012 ...

View 6 Replies View Related

Want 1 To Many Relationship When Child Table Has No Primary Key

Jul 20, 2005

I want to create a 1-many relationship. Parent table has a primarykey, child table has no primary key. The child table does have anindex with all four fields of the parent's PK. How can I do this?Thanks, Bob C.

View 9 Replies View Related

Parent/Child Table Replication

Apr 4, 2008

Hello all gurus out there.

I'm an entre level junior programmer. My question is kind of confusing but I'll try to put it as simple as I can.

First we have a main table called "job1". This table consists the order information. The file_id is the unique id and the primary key for this table. This table also pertains other information such as customer data (max limit 5), job data etc. This table is actively (non-stop) used throughout the day.

We have a non-interactive process which will take customers information from the main table and insert into the child table table "jobcust". Jobcust would have file_id, cust, cust_type. For example, if Job1 table had fiel_id=100 and cust1="Tom" and Cust2="David", now Jobcust will have two records file_id, cust1 and file_id,cust2. The main problem is the child table needs to be updated right away and our non-interactive process is good at doing that.. but it is causing a major DATA LATENCY. I would like to ask you all, if you know any better way of doing this without any process.. like in the back end with a trigger/procedure or something like that.

All you help is appreciated.

Thanks much.

View 5 Replies View Related

Deletion Of Parent And Child Table

Feb 28, 2008

how can we delete parent table as well as child table using a single query applied on parent table, can someone please help me onn this topic? it will be very nice of you guys.

Rahul Arora
07 Batch
NCCE Israna,


######################
IMPOSSIBLE = I+M+POSSIBLE

View 3 Replies View Related

Parent And Child Records From Same Table

Mar 13, 2008

Hi

i have a table named categorymaster

categoryid catname parentid
1 Boxing 0
2 Tennis 0
3 Basketball 0
4 MayWeather 1
5 Tyson 1
6 Clinton woods 1
7 RogerFederer 2
8 Micheal 3
9 Hingis 2

so if i give input say categoryid=1[This falls under main category-boxing]
i need to get result as
1 boxing [main category]
4 mayweather [sub category]
5 tyson [sub category]
6 clinton woods [sub category]

if i give categoryid=5[Note:Tyson]
result should be as
1 boxing [main category]
5 tyson [sub category]

hope u can get my question
Thanks in advance

View 2 Replies View Related

Transact SQL :: Recursive CTE Parent Child Query

Oct 31, 2015

I have a Recursive CTE for TFS database which gives me below results:

Parent (User Story) level 0
             -------------.Task(Dev) and ask(QA) --

level  1
    BUG level 2
                ---------------Task (Dev) and Task(QA)
level2 

So, My ParentID column keeps two ParentId one for User story which keeps the child tasks and child bugs and another for Bug Child tasks

I need to update this results and want to see all of the tasks under User story so the result I want is:

User Story:

 Task(dev and QA)
 Task (Dev and QA ) but its should know that these tasks are the bug tasks.

View 10 Replies View Related

Automatically Adding Records To Child Table When Record Added To Parent Table

Aug 19, 2006

In SQL Server 2000, I have a parent table with a cascade update to a child table. I want to add a record to the child table whenever I add a table to the parent table. Thanks

View 1 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved