[英]SQL Union query error with vb.net
該代碼在很長一段時間內一直有效,直到有人在SQL數據庫中添加了導致Web程序崩潰的新名稱(SE01)。 網絡錯誤表明
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]
代碼工作是使用查詢來通過數據庫查找下一個可用名稱,例如,數據庫中的現有服務器名稱為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 = "*"
當然這是行不通的。 您將一切都放在UXPV的右邊,然后將該值當作數字對待。 但是,對於一條記錄,您將不再有該值的數字。
因此,您需要做的是擺脫不良記錄並更改用戶界面,以便將來無法添加數據類型。 或者,您需要修復代碼以去除所有字母字符。
我意識到我要做的就是添加這樣的代碼來忽略“ SE”,
sqlAddOn = "and Name not like '%j%' and Name not like '%se%'"
sqlAddOnAudit = "and Server not like '%j%' and Server not like '%se%'"
現在,它開始工作並返回到它應該是的搜索方式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.