Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 how to construct this in a CTE?

Author  Topic 

atlzbest
Starting Member

7 Posts

Posted - 2009-12-16 : 15:46:51
Hi guys

I am a BI developer with elementary sql skills. i have an interesting task to "flatten" a recursive table that has multple pk/fk relationships in order to complete the parent/child relationship. Here's how it goes:

the table structure looks like this, its an example i drummed up but mirrors the business req exactly:

[Content] has many [Paragraph],[Sentences], [Words]
[Paragraph] has many [Sentences], [Words]
[Sentences] has many [Words].

[Content] has pkid which contains ids for all the objects.
You only content-paragraph relationship by looking at [Content].pkid = [Paragraph].fkid
You only paragraph-sentence relationship by looking at [Paragraph].pkid = [Sentence].fkid

The idea is to generate a table looking like this

ParentId, ChildId, Type, Qty
-------------------------------

content1, paragraph1, Content, 1
content1, word1, Content, 2
Paragraph1, Sentence1, Paragraph, 2
Paragraph1, Sentence2, Paragraph, 1


Since this requires a bunch of pk/fk relationships to figure out the parent/child relationship would this be built/maintained better in a CTE expression (hints on how to construct?) or in a SSIS package?


Thanks a lot of for your input and suggestions.

yosiasz
Master Smack Fu Yak Hacker

1635 Posts

Posted - 2009-12-16 : 16:04:17
BOL says it is possible

USE AdventureWorks;
GO
WITH DirectReports (ManagerID, EmployeeID, Title, DeptID, Level)
AS
(
-- Anchor member definition
SELECT e.ManagerID, e.EmployeeID, e.Title, edh.DepartmentID,
0 AS Level
FROM HumanResources.Employee AS e
INNER JOIN HumanResources.EmployeeDepartmentHistory AS edh
ON e.EmployeeID = edh.EmployeeID AND edh.EndDate IS NULL
WHERE ManagerID IS NULL
UNION ALL
-- Recursive member definition
SELECT e.ManagerID, e.EmployeeID, e.Title, edh.DepartmentID,
Level + 1
FROM HumanResources.Employee AS e
INNER JOIN HumanResources.EmployeeDepartmentHistory AS edh
ON e.EmployeeID = edh.EmployeeID AND edh.EndDate IS NULL
INNER JOIN DirectReports AS d
ON e.ManagerID = d.EmployeeID
)
-- Statement that executes the CTE
SELECT ManagerID, EmployeeID, Title, Level
FROM DirectReportsINNER JOIN HumanResources.Department AS dp
ON DirectReports.DeptID = dp.DepartmentID
WHERE dp.GroupName = N'Research and Development' OR Level = 0;
GO




<><><><><><><><><><><><><><><><><><><><><><><><><>
If you don't have the passion to help people, you have no passion
Go to Top of Page
   

- Advertisement -