我有一个例程,它从SQL DB中的INT列获取MAX值,并且应该将该数字增加“1”。问题是,当它运行时,它似乎是第一次工作,但每次此后,例程继续返回'1'。我正在寻找的值叫做maxrptnum。例程如下:
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim conn As New SqlConnection("Data Source=server;Initial Catalog=forms;User ID=user;Password=password")
Dim cmd As New SqlCommand
cmd.CommandText = "select max(increment) from forma where rptnum like 'a-@inspinit-%'"
cmd.Parameters.Clear()
cmd.Parameters.Add("@inspinit", SqlDbType.Char).Value = inspinit.Text
cmd.Connection = conn
conn.Open()
maxrptnum = cmd.ExecuteScalar() & String.Empty
If maxrptnum = String.Empty Then
maxrptnum = 1
Me.rptnum.Text = ("A" + "-" + Me.inspinit.Text + "-" + maxrptnum)
Else
Me.rptnum.Text = ("A" + "-" + Me.inspinit.Text + "-" + (maxrptnum + 1))
End If
conn.Close()
saverpt()
End Sub
maxrptnum声明为字符串,但DB类型为int。这可能是问题,但不确定如何解决它。
答案 0 :(得分:1)
如上面的评论所述,您通常不应该执行此操作。桌面上的并发可能会给您带来很大的麻烦 但问题在于查询以及添加参数占位符的方式。将它放在单引号之间会转换文字字符串中的所有内容。
你应该写
cmd.CommandText = @"select max(increment)
from forma where rptnum like @inspinit"
然后,当您添加参数时,
cmd.Parameters.Add("@inspinit", SqlDbType.Char).Value = "a-" + inspinit.Text + "-%"
最后,检索值的代码可以直接使用整数写入,而不是转换字符串中的所有内容
Dim maxrptnum As Integer
Dim result = cmd.ExecuteScalar()
If result Is Nothing Then
maxrptnum = 1
Else
maxrptnum = Convert.ToInt32(result) + 1
End If
Me.rptnum.Text = ("A-" & Me.inspinit.Text & "-" & maxrptnum.ToString())