如何在以下范围内生成唯一收据编号: GA00000-GZ99999?我不允许使用'I'和'O'字母,所以GI00000-GI99999& GO00000-GO99999将被排除在外。
理想情况下,我想在T-SQL中创建它,但也可以在VB.Net中创建它。这个数字将存储在SQL中,我可以在生成下一个数字之前访问它。它们不必是顺序的。
感谢。
答案 0 :(得分:2)
创建允许作为第一个数字的所有字符的array
。
对于任何数字收据ID n
,收据代码为G
+ array[n/1000000]
+ n % 1000000
。
答案 1 :(得分:1)
保留后缀指针。当你的索引包装超过99999时,递增它。检查您的特殊情况和用尽情况(例如Z)。
答案 2 :(得分:1)
这是一个VB.NET版本,可以获得下一个序列号,前一个序列号。我想我已经涵盖了所有案例。
Private Const FirstReceiptNumber As String = "GA00000"
Public Function GenerateReceiptNumber(ByVal lastNumber As String) As String
If lastNumber.Length <> 7 Then
Throw New ArgumentException("Incorrect length", "lastNumber")
End If
If lastNumber.StartsWith("G") = False Then
Throw New ArgumentException("Incorrect start character", "lastNumber")
End If
Dim letterPortion As Char = lastNumber.Chars(1)
If letterPortion < "A"c Or letterPortion > "Z"c Then
Throw New ArgumentException("Non-letter second character", "lastNumber")
End If
If letterPortion = "I"c Or letterPortion = "O"c Then
Throw New ArgumentException("Invalid second character", "lastNumber")
End If
Dim numericPortionString As String = lastNumber.Substring(2)
Dim numericPortion As Integer
If Integer.TryParse(numericPortionString, numericPortion) = False Then
Throw New ArgumentException("Invalid numeric portion", "lastNumber")
End If
If numericPortion = 99999 Then
If letterPortion = "Z"c Then
Throw New ArgumentException("No more receipt numbers possible", "lastNumber")
End If
numericPortion = 0
letterPortion = letterPortion + Chr(1)
If letterPortion = "I"c Or letterPortion = "O"c Then
letterPortion = letterPortion + Chr(1)
End If
Else
numericPortion = numericPortion + 1
End If
Return String.Format("G{0}{1:00000}", letterPortion, numericPortion)
End Function
答案 3 :(得分:1)
我决定这样做:
CREATE FUNCTION [dbo].[fn_generateReceiptNumber]()
RETURNS NCHAR(7)
AS
BEGIN
-- Declare the return variable here
DECLARE @result NCHAR(7);
DECLARE @prefix NCHAR(1);
DECLARE @suffix INT;
DECLARE @currentMax NCHAR(7);
SELECT @currentMax = MAX(ISNULL(fp.CustomReceiptNo, 'GA00001')) FROM dbo.FinPayment fp;
SELECT @prefix = SUBSTRING(@currentMax,2,1);
SELECT @suffix = CAST(SUBSTRING(@currentMax,3,7) AS INT);
IF((@suffix + 1) > 99999)
BEGIN
SELECT @suffix = 0;
END
ELSE
BEGIN
SELECT @suffix = @suffix + 1;
END
IF(@suffix = 0)
BEGIN
IF(@prefix = 'Z')
BEGIN
RETURN -1;
END
ELSE
BEGIN
IF(NCHAR(UNICODE(@prefix)+1) IN ('I', 'O'))
BEGIN
SELECT @prefix = NCHAR(UNICODE(@prefix)+2);
END
ELSE
BEGIN
SELECT @prefix = NCHAR(UNICODE(@prefix)+1);
END
END
END
-- Return the result of the function
SELECT @result = NCHAR(71) + @prefix + CAST(RIGHT('00000' + RTRIM(@suffix), 5) AS NCHAR(5));
RETURN @result;
END
GO
感谢大家的投入。 史蒂夫。