0

我的表中有一个UserID字段,我需要在我的应用程序中获取该值,并且每当我想添加新记录时,它应该按值 '1' 递增

所以这就是我试图从我的表中获取最后一个 ID的方式。

例如,我的值为“A000”,我需要将该值增加“1”,使其变为“A001”,依此类推……在PinnyM指出的“A999”之后,它应该变为'A1000'

我不想从数据库编写任何存储过程或任何其他方式。我想使用我现有的代码以更简单的方式来完成它。

 Dim strConnection As String = "Data Source=.\SqlExpress;Initial Catalog=Subscription;Integrated Security=True"
 Dim con As New SqlConnection(strConnection)
 con.Open()
 Dim comm As New SqlCommand
 comm.CommandText = "SELECT MAX(UserID) FROM Customers"
 comm.Connection = con
 Dim MaxUserID As Object = comm.ExecuteScalar()
 txtID.text=MaxUserID
4

2 回答 2

0

我通过这种方式设法使其工作:

Public Function IncrementString(ByVal Sender As String) As String
    Dim Index As Integer
    For Item As Integer = Sender.Length - 1 To 0 Step -1
        Select Case Sender.Substring(Item, 1)
            Case "000" To "999"
            Case Else
                Index = Item
                Exit For
        End Select
    Next
    If Index = Sender.Length - 1 Then
        Return Sender & "1" '  Optionally throw an exception ?
    Else
        Dim x As Integer = Index + 1
        Dim value As Integer = Integer.Parse(Sender.Substring(x)) + 1
        Return Sender.Substring(0, x) & value.ToString()
    End If
End Function
于 2013-02-03T04:12:13.140 回答
-1

基于以上评论,我建议:

comm.CommandText = "SELECT 'A' + RIGHT('000', CAST((MAX(primary_key) + 1) as nvarchar(255)), 3) FROM Customers"

这是做什么的:

  • 获取最后一个key并加1
  • 转换为 nvarchar
  • 必要时用 0 填充(最多 3 个位置)

我绝对不会尝试使用基于字符的键来执行此操作,因为它UserID似乎已构建。另外,请注意,这不是原子的,并且不能保证另一个连接不会在您之前插入一行。所以它确实返回了一个可能实际上并不正确的乐观值。如果这对您不起作用,请考虑让 IDENTITY 为您完成工作并在使用创建行后获取值SCOPE_IDENTITY()

于 2013-02-03T03:55:26.440 回答