我在最後的select語句有問題。我想要做的是選擇兩個級別,但即時通過此聲明沒有結果。請注意,如果@Level爲1,我不想低於1,否則可能會混淆結果,因此可能會出現一個條件以及select語句where子句二的條件
它所在的部分@Level = @Level -1我是具有
FROM c WHERE c.Level = @Level AND c.Level = @Level - 1 ORDER BY Level ASC
或這一個
FROM c WHERE c.Level BETWEEN @Level AND c.Level - 1 ORDER BY Level ASC
SQL問題
DECLARE @Department TABLE
(
Id INT NOT NULL,
Name varchar(50) NOT NULL,
ParentId int NULL
)
INSERT INTO @Department SELECT 1, 'Toys', null
INSERT INTO @Department SELECT 2, 'Computers', null,
INSERT INTO @Department SELECT 3, 'Consoles', 2
INSERT INTO @Department SELECT 4, 'PlayStation 3', 3
INSERT INTO @Department SELECT 5, 'Xbox 360', 2
INSERT INTO @Department SELECT 6, 'Games', 1
INSERT INTO @Department SELECT 7, 'Puzzles', 6
INSERT INTO @Department SELECT 8, 'Mens Wear', null
INSERT INTO @Department SELECT 9, 'Mens Clothing', 8
INSERT INTO @Department SELECT 10, 'Jackets', 9
INSERT INTO @Department SELECT 11, 'Shoes', 9
INSERT INTO @Department SELECT 12, 'Rain Coats', 10
DECLARE @Level int = 4
;WITH c AS
(
SELECT Id, ParentId, Name, 1 AS Level
FROM @Department
WHERE ParentId IS NULL
UNION ALL
SELECT t.Id, t.ParentId, T.Name, c.Level + 1 AS Level
FROM @Department T
INNER JOIN c on t.ParentId = c.Id
)
SELECT Id, ParentId, Name, Level
FROM c WHERE c.Level = @Level AND c.Level = @Level - 1 ORDER BY Level ASC
FROM c WHERE c.Level BETWEEN @Level AND @Level - 1 ORDER BY Level ASC
顯示你想要的結果。 – JeffO 2011-12-22 23:26:11
如果你只進入一個級別,你可以加入這個表格,並將你的條件放在on子句中。 – JeffO 2011-12-22 23:26:55