【发布时间】:2017-09-22 05:47:06
【问题描述】:
我在对表格进行有效排序时遇到了一些麻烦(表格包含大量行,因此任何优化都会产生很大的不同)。
我目前拥有的给出正确结果 (11) 的是下面的代码。
BEGIN TRANSACTION
CREATE TABLE #tPallets
(
PalletNumber bigint,
Placement nvarchar(4)
)
INSERT INTO #tPallets VALUES(100000, 'B')
INSERT INTO #tPallets VALUES(100001, 'M1')
INSERT INTO #tPallets VALUES(100002, 'M2')
INSERT INTO #tPallets VALUES(100003, 'M3')
INSERT INTO #tPallets VALUES(100004, 'M4')
INSERT INTO #tPallets VALUES(100005, 'M5')
INSERT INTO #tPallets VALUES(100006, 'M6')
INSERT INTO #tPallets VALUES(100007, 'M7')
INSERT INTO #tPallets VALUES(100008, 'M8')
INSERT INTO #tPallets VALUES(100009, 'M9')
INSERT INTO #tPallets VALUES(100010, 'M10')
INSERT INTO #tPallets VALUES(100011, 'M11')
SELECT
TOP 1 CASE
WHEN Placement LIKE 'M%' THEN CONVERT(int, SUBSTRING(Placement,2, len(Placement)-1))
ELSE 0
END AS PALLET_PLACEMENT
FROM
#tPallets
ORDER BY
1 DESC
ROLLBACK TRANSACTION
因此,如果在这种特定情况下可能的话,我正在寻找一种方法来加快选择速度。
我不会认为这是答案的重复。由于线程中没有答案会使执行时间更快,而无需在 C# 中进行排序(而不是在 TSql 中进行排序)。而且我很难相信 TSql 本身没有更快的方法。
【问题讨论】:
-
值的结构是否一致?总是 1 个字母,然后是 0 - 2 个数字?字母总是大写吗?
Placement的值是否会改变? -
@SolomonRutzky 它总是 B 或 M1 - M150(最坏的情况)。很抱歉回答得太晚了,没有看到评论。
标签: sql-server tsql