vb.net 如何生成自定义 ID
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22706830/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to generate Custom ID
提问by kolapopo
I want to create a custom value for the ID. For example, it will start with "CR00001" and after that it will increment the numerical portion (e.g. CR00002) when I save the data for the second time.
我想为 ID 创建一个自定义值。例如,它将以“CR00001”开头,之后当我第二次保存数据时它会增加数字部分(例如CR00002)。
Here is the code I am using:
这是我正在使用的代码:
Dim cr_id As String
cr_id = "CR00001"
Dim iReturn As Boolean
Using SQLConnection As New MySqlConnection(strConnectionString)
Using sqlCommand As New MySqlCommand()
sqlCommand.Connection = SQLConnection
With sqlCommand
.CommandText = "INSERT INTO cr_record(idcr_record,Emplid,isu,Nama,date1,DeptDesc,email,change1,reasonchange,problem,priority,reasondescription,systemrequest,attachment) VALUES (@cr_id,@Emplid,@isu,@Nama,@date1,@DeptDesc,@email,@change1,@reasonchange,@problem,@priority,@reasondescription,@systemrequest,@attachment)"
.CommandType = Data.CommandType.Text
.CommandTimeout = 5000
.Parameters.AddWithValue("@cr_id", cr_id)
采纳答案by Sarjit Delivala
When you want to generate a new ID, write one function for generating the ID, and copy this code there. Keep the return type as Stringto return newId.
当你想生成一个新的 ID 时,编写一个生成 ID 的函数,并将这段代码复制到那里。保持返回类型为Stringreturn newId。
Dim newId As String
Dim stringId As String
Dim intId As Integer
Dim conn As New System.Data.SqlClient.SqlConnection("Your database query string")
Dim adpt As New System.Data.SqlClient.SqlDataAdapter("Select id from tableName Where date = (SELECT max(date) from tableName)", conn) 'Where tableName is you table
Dim ds As New DataSet
adpt.Fill(ds)
If ds.Tables(0).Rows.Count = 0 Then 'This will check whether any records are there or not
newId = "CR00001" ' If records are not there then this id will be returned
Else
stringId = ds.Tables(0).Rows(0).Item(0).ToString 'This will store your id in string format
intId = stringId.Substring(2) ' This will store only integer values from that id
intId += 1 ' Increment id by 1
newId = String.Concat("CR", intId) ' Creating new Id incremented by 1
End If
Return newId

