在vb.net中自动递增nvarchar值 [英] Auto Increment nvarchar value in vb.net
问题描述
我的表中有一个 UserID 字段,我需要在我的应用中获取该值,并且每当我想要添加新记录时,它都应该按值"1"递增'.
I'm having a UserID field in my table and I need to get that value in my app and whenever I would like to add a new record it should increment by value '1'.
这就是我要从表中获取最后一个ID 的方法.
So this is how I'm trying to get the last ID enetered from my table.
例如,我的值为"A000" ,我需要将该值加'1',以使其变为"A001 "等.在PinnyM'指出的'A999'之后,它应该变成'A1000'.
For Example I'm having a value as "A000" and I need to increment that value by '1' so that it should become "A001" and so on..and after 'A999' as pointed out by PinnyM' it should become 'A1000'.
我不想从数据库编写任何存储过程或其他任何方式.我想使用现有代码以一种更简单的方式做到这一点.
I don't want to write any stored procedures or anyother way from database.I would like to do it in a simpler way using my existing code.
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
推荐答案
通过这种方式,我设法使它起作用:
I got it managed to work by doing it this way:
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
这篇关于在vb.net中自动递增nvarchar值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!