如何使用我在SQL Server存储过程中提供的格式增加数字

时间:2018-12-29 05:56:59

标签: sql-server stored-procedures

我正在使用SQL Server存储过程来增加自定义数字。我有一个自动编号列,它分配给@LASTNUMBER变量:

SET @STOCK_LEDGER_NUMBER = 'SLL' + '-' + RIGHT(('0000'+ CAST((@LASTNUMBER + 1)AS VARCHAR)),4)
  • 第一个输出:'SLL-0001'
  • 我可以返回的最后一个输出:'SLL-9999'

使用此代码,我最多只能将数字增加到9999。

当自动编号设置为10000时,此代码返回“ SLL-0000”。但我需要显示为“ SLL-10000”,下一个数字应为“ SLL-10001”

请帮助我

2 个答案:

答案 0 :(得分:4)

如果要支持五位数,只需将代码行更改为:

SET @STOCK_LEDGER_NUMBER = 'SLL' + '-' + RIGHT(('00000'+ CAST((@LASTNUMBER + 1) AS VARCHAR(5))), 5)

答案 1 :(得分:1)

试一下...它将处理任何正的INT值而无需进行任何修改...

DECLARE 
    @last_number INT,
    @digit_count INT,
    @rep_start INT,
    @stock_ledger_number VARCHAR(14);

SELECT 
    @last_number = 10000,
    @digit_count = FLOOR(LOG10(@last_number + 1) + 1),
    @rep_start = (ABS(4 - @digit_count) + (4 - @digit_count)) / 2,
    @stock_ledger_number = STUFF('SLL-0000', 5 + @rep_start, @digit_count, CONVERT(VARCHAR(10), @last_number + 1))

SELECT last_number = @last_number, stock_ledger_number = @stock_ledger_number;

结果...

last_number stock_ledger_number
----------- -------------------
10000       SLL-10001

还有其他一些示例...

last_number stock_ledger_number
----------- -------------------
1           SLL-0002

last_number stock_ledger_number
----------- -------------------
55          SLL-0056

last_number stock_ledger_number
----------- -------------------
332         SLL-0333

last_number stock_ledger_number
----------- -------------------
2018        SLL-2019

last_number stock_ledger_number
----------- -------------------
12345       SLL-12346

last_number stock_ledger_number
----------- -------------------
1234567890  SLL-1234567891

last_number stock_ledger_number
----------- -------------------
2147483646  SLL-2147483647

当然,您并不仅限于使用标量变量一次执行这些操作。您可以分批地将它们启动...

-与上述标量变量版本相同的逻辑,但适用于在一次执行中生成多个值。

DECLARE @last_number INT = 9900;

WITH    
    cte_Tally AS (
        SELECT TOP (15000)
            n = ROW_NUMBER() OVER (ORDER BY o1.object_id) + @last_number
        FROM
            sys.objects o1
            CROSS JOIN sys.objects o2
        )
SELECT 
    STOCK_LEDGER_NUMBER = CONVERT(VARCHAR(14), STUFF('SLL-0000', 5 + rs.rep_start, dc.digit_count, CONVERT(VARCHAR(10), t.n)))
FROM
    cte_Tally t
    CROSS APPLY ( VALUES ( CONVERT(INT, FLOOR(LOG10(t.n) + 1))) ) dc (digit_count)
    CROSS APPLY ( VALUES ((ABS(4 - dc.digit_count) + (4 - dc.digit_count)) / 2) ) rs (rep_start);
GO