2014-09-22 55 views
0

代碼長時間工作很長時間,直到有人在SQL數據庫中添加新名稱(SE01),導致Web程序崩潰。顯示的網頁錯誤SQL Union與vb.net的查詢錯誤

System.InvalidCastException: Conversion from string "SE01" to type 'Integer' 
is not valid. 

與其他SQL聯合查詢錯誤一起,

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 = "*" 
+0

你沒有提供的信息就是它在'y = CType(dr(「Name」),Integer)行上的失敗。 – 2014-09-22 13:44:18

回答

1

當然,這並不工作。您正在將UXPV的所有內容都處理好,然後像數字一樣處理該值。但是,對於一條記錄,您不再具有該值的數字。

因此,您需要做的是擺脫不良記錄並更改用戶界面,以便將來無法添加數據類型。或者您需要修復代碼以去除所有字母字符。

0

我意識到,我必須做的就是添加到忽略「SE」像這樣,

sqlAddOn = "and Name not like '%j%' and Name not like '%se%'" 
sqlAddOnAudit = "and Server not like '%j%' and Server not like '%se%'" 

現在的工作,回到搜索它想成爲的方式。