我发现了这个带有 CTE 的 SQL 递归的好例子,但未能将它应用到我的表中:
我有下表(ObjectStates):
ID Title ParentID
1 Draft null
2 Green null
3 Red null
4 Foo 1
5 Bar 4
我正在尝试创建一个在查询时返回“主要”状态的函数。例子:
GetMainState(5)
-- Shall return 1
GetMainState(4)
-- Shall return 1
GetMainState(2)
-- Shall return 2
我到目前为止:
CREATE FUNCTION [dbo].[GetMainObjectState] (@ObjectStateID INT)
RETURNS TABLE
AS
RETURN
(
WITH StateRecurcsion(ID, ParentID, Level) AS
(
SELECT ID, ParentID, 0
FROM ObjectStates
WHERE ID = @ObjectStateID
UNION ALL
SELECT uOS.ID, uOS.ParentID, sOS.Level+1
FROM ObjectStates uOS, StateRecurcsion sOS
WHERE uOS.ParentID= sOS.ID
)
SELECT os.ID, os.Title, sos.Level
FROM ObjectStates os, StateRecurcsion sos
WHERE os.ID = sos.ID
)
GO
我尝试按照上面显示的教程创建函数,但不知何故我没有得到正确的结果。