根据经验,我编写代码的方式是我在 12 个月内不费吹灰之力就能理解的方式。同样,这意味着我希望其他开发人员也能轻松理解这件事。
所以在这种情况下,我不会在ORDER BY
子句中隐藏这个神秘的逻辑。SELECT
通过将值作为子句的一部分,我会让事情变得更加透明。
DECLARE @t table (
DebitNote nvarchar(10)
);
INSERT INTO @t (DebitNote)
VALUES ('1/2013')
, ('1/2014')
, ('2/2013')
, ('3/2013')
, ('5/2010')
, ('25/2013')
, ('115/2013')
, ('26/2014');
SELECT DebitNote
FROM (
SELECT DebitNote
, CharIndex('/', DebitNote) As position_of_slash
, Cast(SubString(DebitNote, 0, CharIndex('/', DebitNote)) As int) As first_part
, SubString(DebitNote, CharIndex('/', DebitNote) + 1, 10) As last_part -- Note that the last parameter of the SubString() function here
-- equals the length of the field in question
FROM @t
) As x
ORDER
BY last_part
, first_part;
如果愿意,可以在 CTE 中进行最后一个查询
; WITH component_parts AS (
SELECT DebitNote
, CharIndex('/', DebitNote) As position_of_slash
, Cast(SubString(DebitNote, 0, CharIndex('/', DebitNote)) As int) As first_part
, SubString(DebitNote, CharIndex('/', DebitNote) + 1, 10) As last_part -- Note that the last parameter of the SubString() function here
-- equals the length of the field in question
FROM @t
)
SELECT DebitNote
FROM component_parts
ORDER
BY last_part
, first_part;