17.06.2013 Views

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

AS<br />

BEGIN<br />

(<br />

EmployeeID int NOT NULL,<br />

ManagerID int NULL<br />

)<br />

/* Since we’ll need to call this function recursively - that is once for each<br />

** reporting employee (to make sure that they don’t have reports of their<br />

** own), we need a holding variable to keep track of which employee we’re<br />

** currently working on. */<br />

DECLARE @Employee AS int;<br />

/* This inserts the current employee into our working table. The significance<br />

** here is that we need the first record as something of a primer due to the<br />

** recursive nature of the function - this is how we get it. */<br />

INSERT INTO @Reports<br />

SELECT EmployeeID, ManagerID<br />

FROM HumanResources.Employee2<br />

WHERE EmployeeID = @EmployeeID;<br />

/* Now we also need a primer for the recursive calls we’re getting ready to<br />

** start making to this function. This would probably be better done with a<br />

** cursor, but we haven’t gotten to that chapter yet, so.... */<br />

SELECT @Employee = MIN(EmployeeID)<br />

FROM HumanResources.Employee2<br />

WHERE ManagerID = @EmployeeID;<br />

/* This next part would probably be better done with a cursor but we haven’t<br />

** gotten to that chapter yet, so we’ll fake it. Notice the recursive call<br />

** to our function! */<br />

WHILE @Employee IS NOT NULL<br />

BEGIN<br />

INSERT INTO @Reports<br />

SELECT *<br />

FROM fnGetReports(@Employee);<br />

END<br />

RETURN;<br />

END<br />

GO<br />

SELECT @Employee = MIN(EmployeeID)<br />

FROM HumanResources.Employee2<br />

WHERE EmployeeID > @Employee<br />

AND ManagerID = @EmployeeID;<br />

Chapter 13: User-Defined Functions<br />

I’ve written this one to provide just minimal information about the employee and his or her manager —<br />

I can join back to the Employee2 table, if need be, to fetch additional information. I also took a little bit<br />

of liberty with the requirements on this one and added in the selected manager to the results. This was<br />

done primarily to support the recursion scenario and also to provide something of a base result for our<br />

421

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!