SQL增量限制

时间:2018-10-11 04:53:25

标签: sql-server tsql

DECLARE @AbbrvCount INT    
DECLARE @Abbreviation NVARCHAR(50)

SET @Abbreviation = 'PHMY'
SET @AbbrvCount = (2+ LEN(@Abbreviation)+ 1)    

DECLARE @CDCode NVARCHAR(50)

SET @CDCode = (SELECT CONCAT('CD', @Abbreviation, ISNULL((SELECT TOP 1 SUBSTRING(CashierDepositCode, @AbbrvCount, 50 - @AbbrvCount)
               FROM CashierDepositSlips
               WHERE SUBSTRING(CashierDepositCode, 3, LEN(@Abbreviation)) = @Abbreviation
               ORDER BY CashierDepositCode DESC) + 1, '1')))

我的@CDCode达到"CDPHMY10"时遇到问题,它不再增加。帮助将不胜感激。我想将其增加到"CDPHMY11",依此类推。.谢谢

1 个答案:

答案 0 :(得分:0)

您需要先提取数字部分,然后转换为整数,然后才能按照所需的方式进行排序

STUFF(CashierDepositCode, 1, @AbbrvCount - 1, ''),这将提取代码的数字部分。但是结果仍然是字符串。因此,如果您订购该产品,则9

之前将是'10'。

更改为以下内容

SET @CDCode =   
    (
        SELECT CONCAT('CD', 
                      @Abbreviation, 
                      ISNULL(( SELECT TOP 1 STUFF(CashierDepositCode, 1, @AbbrvCount - 1, '')
                               FROM       CashierDepositSlips
                               WHERE      SUBSTRING(CashierDepositCode, 3, LEN(@Abbreviation)) = @Abbreviation
                               ORDER BY   CONVERT(INT, STUFF(CashierDepositCode, 1, @AbbrvCount - 1, '')) DESC) + 1, '1'))
    )

此外,如果前缀CD是固定的,那么最好将WHERE更改为

WHERE CashierDepositCode LIKE 'CD' + @Abbreviation + '%'