Have you experimented with
TOP
? What were the results?
SELECT TOP 3 Row_Number()...
Updated. The last 3 rows can be achieved if you reverse the ORDERing you have in place. Here is the full query based upon this:
;WITH emp_hierarachy AS(
SELECT emp = EmployeeId, EmployeeId, Manager, Firstname + ' ' + surname as [name], Position
FROM tblEmployee
UNION ALL
SELECT rs.emp, t.EmployeeId, t.Manager, t.Firstname + ' ' + surname as [name], t.Position
FROM tblEmployee t
INNER JOIN emp_hierarachy rs ON t.EmployeeId = rs.Manager
)
SELECT TOP 3 id = Row_Number() OVER (ORDER BY (SELECT 1))
, rs.name
, rs.Position
FROM emp_hierarachy rs
WHERE rs.emp = 179
ORDER BY ID
Notes/Questions/Questions
Please note that the
name field is wrapped in square brackets. Name is one of them words that is certain contexts is special.I generally would avoid using them.
In your commented out AND clause, you are using != for inequality. While this is valid in SQL Server, the ANSI standard is to use
<>
; so the portability of this code may be limited.
The CTE seems to be gathering more data than it needs to; only the EmployeeID, [name] and position columns are called upon, and the UNION ALL is going to add in duplicate records.
I would be interested in seeing sample data and the results you expect to come out; as I do not know the schema of these tables but I think this could be greatly reduced codewise