代码在很长一段时间内都运行良好,直到有人在SQL数据库中添加新名称(SE01)导致Web程序崩溃。网页错误显示
System.InvalidCastException: Conversion from string "SE01" to type 'Integer'
is not valid.
以及其他SQL Union查询错误,
SELECT Substring([Name],@lenSrv, 8) as Name
FROM [dbo].[ServerOwners]
where [Name] like @Srv
and Name not like '%j%'
union
SELECT Substring([Server],@lenSrv, 8) as Name
FROM [dbo].[AuditLog]
where log='delete'
and [DATE] > (GETDATE() - 60)
and [SERVER] like @Srv
and Server not like '%j%'
order by [name]
代码作业是使用查询通过数据库查找下一个可用名称,例如, 数据库中存在的servername是UXVP001,代码将找到免费的UXVP002。现在有人在SQL数据库中添加了UXVPSE01,这似乎导致读取查询崩溃。我希望它被接受/忽略新名称而不会出错。
以下是搜索数据库的剪切的vb代码,
srv = "UXPV"
sqlAddOn = "and Name not like '%j%'"
sqlAddOnAudit = "and Server not like '%j%'"
"Logic to find next available name"
"1. select the numbers to the right of the characters"
"2. loop all values and find first missing number"
Dim sqlConn As New System.Data.SqlClient.SqlConnection((ConfigurationManager.ConnectionStrings("SOCT").ConnectionString))
Dim strSql As String = "SELECT Substring([Name],@lenSrv, 8) as Name FROM [dbo].[ServerOwners] where [Name] like @Srv " & sqlAddOn
strSql &= " union "
strSql &= "SELECT Substring([Server],@lenSrv, 8) as Name FROM [dbo].[AuditLog] where log='delete' and [DATE] > (GETDATE() - 60) and [SERVER] like @Srv " & sqlAddOnAudit
strSql &= " order by [name]"
Dim cmd As New System.Data.SqlClient.SqlCommand(strSql, sqlConn)
Dim dr As System.Data.SqlClient.SqlDataReader
LabelError.Text = ""
Dim x As Integer = 1
Dim y As Integer = 1
Dim foundYet As Boolean = False
Try
sqlConn.Open()
cmd.Parameters.AddWithValue("@lenSrv", srv.Length + 1)
cmd.Parameters.AddWithValue("@Srv", srv & "%")
dr = cmd.ExecuteReader()
While dr.Read() And foundYet = False
LabelError.Text = LabelError.Text & dr("Name") & " | "
y = CType(dr("Name"), Integer)
If x = y Then
"keep going"
x = x + 1
Else
"you found first available number"
foundYet = True
End If
End While
dr.Close()
cmd.Dispose()
Catch ex As Exception
hide()
PanelError.Visible = True
LabelError.Text = ex.ToString() & "<hr/>" & strSql
Finally
sqlConn.Dispose()
End Try
"make sure leading zeros are present"
" 000"
Dim fmt As String = "00#"
tbAdd_ServerName.Text = srv & x.ToString(fmt)
tbAdd_ServerName.Enabled = False
tbAdd_TM.SelectedValue = "*"
答案 0 :(得分:1)
当然这不起作用。您正在将UXPV右侧的所有内容都拿走,然后将该值视为数字。但是,对于一条记录,您不再拥有该值的数字。
因此,您需要做的是摆脱不良记录并更改用户界面,以便将来无法添加数据类型。或者您需要修复代码以删除所有字母字符。
答案 1 :(得分:0)
我意识到我所要做的就是添加忽略“SE”,就像这样,
sqlAddOn = "and Name not like '%j%' and Name not like '%se%'"
sqlAddOnAudit = "and Server not like '%j%' and Server not like '%se%'"
现在它正在工作并回到它想象的方式进行搜索。