我認爲你最好的辦法是將數據轉換成自然排序的東西。如果你的樹結構總是少於99個孩子,你可以創建一個像下面這樣的函數。您只需在排序函數中使用「GetTreeStructureSort(columnName)」。 (如果你有3位數字的可能性,你可以調整這是更直觀。)
CREATE FUNCTION GetTreeStructureSort
(
-- Add the parameters for the function here
@structure varchar(500)
)
RETURNS varchar(500)
AS
BEGIN
DECLARE @sort varchar(500)
-- Add a hyphen to the beginning and end to make all the numbers from 1 to 9 easily replaceable
SET @sort = '-' + @structure + '-'
-- Replace each instance of a one-digit number to a two-digit representation
SELECT @sort = REPLACE(@sort, '-1-', '-01-')
SELECT @sort = REPLACE(@sort, '-2-', '-02-')
SELECT @sort = REPLACE(@sort, '-3-', '-03-')
SELECT @sort = REPLACE(@sort, '-4-', '-04-')
SELECT @sort = REPLACE(@sort, '-5-', '-05-')
SELECT @sort = REPLACE(@sort, '-6-', '-06-')
SELECT @sort = REPLACE(@sort, '-7-', '-07-')
SELECT @sort = REPLACE(@sort, '-8-', '-08-')
SELECT @sort = REPLACE(@sort, '-9-', '-09-')
-- Strip off the first and last hyphens that were added at the beginning.
SELECT @sort = SUBSTRING(@sort, 2, LEN(@sort) - 2)
-- Return the result of the function
RETURN @sort
END
這將轉換這些結果:
1
1-10
1-3
2
成這樣:
01
01-03
01-10
02
我用以下代碼測試了這個:
DECLARE @something varchar(255)
set @something = '1-10-3-21'
SELECT dbo.GetTreeStructureSort(@something)
用零填充數字<10正是我所需要的。當它被指出時很明顯。謝謝你這樣一個非常詳細的答案。 – drewm