将整数通配符传递给SQL选择查询



我在构建的应用程序中有一个搜索功能,操作员可以根据日期、跟踪号码(运单(或发件人姓名(或三者的组合(进行搜索。

按任何组合搜索都有效。。。直到运单文本框为空。如果它是空的,我会得到这个错误:

System.FormatException:"无法将参数值从字符串转换为Int64。">

这可能很明显,但运单字段是一个整数(bigint(。

我试着设置它,这样,如果运单字段为空,它将包括基于其他搜索参数的所有适用运单号。代码如下,很明显,原因是"%"不是整数的一部分。我试着把它搞砸了,但没有成功,我想知道是否应该使用某种形式的正则表达式把它联系在一起?

SELECT 
LabID, GivenName, Surname, DOB, Sex, Service, Specimen, 
ReferDate, WaybillNo, SendDate
FROM 
US_Biotek
WHERE
SenderName LIKE @SenderName 
AND WaybillNo LIKE @WaybillNo 
AND SendDate BETWEEN @StartDate AND @EndDate
", conn)
cmd.Parameters.Add("@StartDate", SqlDbType.Date).Value = dateFrom.Value
cmd.Parameters.Add("@EndDate", SqlDbType.Date).Value = dateTo.Value
If cbName.SelectedText.Length > 5 Then
cmd.Parameters.Add("@SenderName", SqlDbType.VarChar).Value = cbName.SelectedItem
Else
cmd.Parameters.Add("@SenderName", SqlDbType.VarChar).Value = "%"
End If
If txtWBno.Text.Length = 12 Then
Dim a As Int64 = Convert.ToInt64(txtWBno.Text)
cmd.Parameters.Add("@WaybillNo", SqlDbType.BigInt).Value = a
ElseIf txtWBno.Text.Length < 12 Then
cmd.Parameters.Add("@WaybillNo", SqlDbType.BigInt).Value = "%"
End If
conn.Open()

如果文本框为空,最终目标是让它选择所有运单,如果文本长度在1到11之间(应该是12(,则抛出错误(对该部分进行排序(,或者如果输入了正确的数字,则找到特定的运单。

在收到评论后,我最终将SQL中的列更改为文本字段,并找到了一种只允许在文本框中使用数字字符的方法。

Private Sub txtWBNo_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtWBno.KeyPress
If Not Char.IsNumber(e.KeyChar) AndAlso Not Char.IsControl(e.KeyChar) Then
e.Handled = True
End If
End Sub
Private Sub txtWBNo_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtWBno.TextChanged
Dim digitsOnly As Regex = New Regex("[^d]")
txtWBno.Text = digitsOnly.Replace(txtWBno.Text, "")
End Sub

文本框有一个长度限制集,我也在参数中定义了字符串长度。

If cbName.SelectedText.Length > 5 Then
cmd.Parameters.Add("@SenderName", SqlDbType.VarChar, 90).Value = cbName.SelectedItem
Else
cmd.Parameters.Add("@SenderName", SqlDbType.VarChar, 90).Value = "%"
End If

If txtWBno.Text.Length = 12 Then
cmd.Parameters.Add("@WaybillNo", SqlDbType.VarChar, 12).Value = txtWBno.Text
ElseIf txtWBno.Text.Length < 12 Then
cmd.Parameters.Add("@WaybillNo", SqlDbType.VarChar, 12).Value = "%"
End If

感谢大家朝着正确的方向推动。

最新更新