I’m not sure if such is possible in SQL Server’s database?
Say, I have a table:
id INT
nm NVARCHAR(256)
cid INT --references [id]
and hypothetical data:
id nm cid
1 Name 1 0
2 Name 2 0
3 Name 3 1
4 Name 4 3
5 Name 5 2
6 Name 6 4
7 Name 7 2
And the logic for selection should be as follows:
-
Say, we have the original id, let’s call it N.
-
Then we have a lookup id, let’s call it X. Then we do:
SELECT [cid] FROM [TableName] WHERE [id]=X
and check if the result is equal to N. If yes, then we return [nm] for that record. If the result is 0, then we return Null. If result is something else we do the same selection, except X is now the result value.
I can obviously do this with C# but I’m curious if such is possible to wrap up in a pure SQL statement?
PS. Just to illustrate this with my table above, if N is 1 and X is 6, then we get:
SELECT [cid] FROM [TableName] WHERE [id]=6 --results is 4 (not N or 0, then continue)
SELECT [cid] FROM [TableName] WHERE [id]=4 --results is 3 (not N or 0, then continue)
SELECT [cid] FROM [TableName] WHERE [id]=3 --results is 1 (is N, then return "Name 1")
or if N is 1 and X is 7, we get:
SELECT [cid] FROM [TableName] WHERE [id]=7 --results is 2 (not N or 0, then continue)
SELECT [cid] FROM [TableName] WHERE [id]=2 --results is 0 (is 0, then return Null)
EDIT:
I need this to run under SQL Server 2008.
Recursive CTEs can do this. It would look like this:
The idea is that a CTE can refer to itself in the second part of a
UNION ALLclause, and it will evaluate the second part until it generates no more results, or an internal limit is reached.