提问人:BrettFK 提问时间:10/27/2023 最后编辑:jmcilhinneyBrettFK 更新时间:10/27/2023 访问量:50
vb.NET SQL 查询 - 使用参数筛选浮点列时出现“>附近的语法不正确”
vb.NET SQL Query - "Incorrect syntax near >" when filtering float column using parameter
问:
我有一个应用程序,只需按一下按钮,它就会显示按服务缩写和数值(如适用)过滤的数据列表。
由于某种原因,我无法在不引起异常的情况下使数值的参数起作用。数值列为“number_result”,数据类型为 float。即使文本框中没有值,也会发生这种情况,该值设置为仅允许使用数字字符:
Private Sub txtResultAbove_TextChanged(sender As Object, e As EventArgs) Handles txtResultAbove.TextChanged
Dim digitsOnly As Regex = New Regex("[^\d]")
txtResultAbove.Text = digitsOnly.Replace(txtResultAbove.Text, "")
End Sub
最初,我尝试将参数作为字符串插入,因为我正在寻找 >= 50(例如),将其用作查询:
Using cmd As New SqlCommand("SELECT rq.request_id As 'Request ID', svc.service_abbrev As 'Service', concat(do.dr_first_name, ' ', do.dr_surname) As Doctor, rq.collection_dt as 'Collected', rq.entry_date As 'Received', concat(rqs.number_result, rqs.text_result) as 'Result'
FROM dbo.requests_services rqs
LEFT JOIN services svc ON svc.service_id = rqs.service_id
LEFT JOIN requests rq ON rq.request_id = rqs.request_id
LEFT JOIN doctors do ON do.doctor_id = rq.doctor_id
WHERE rqs.number_result @numRes AND rq.entry_date BETWEEN @StartDate AND @EndDate AND svc.service_abbrev LIKE @SvcAbb
ORDER BY rqs.service_id ASC
", conn)
cmd.Parameters.Add("@StartDate", SqlDbType.Date).Value = dateFrom.Value
cmd.Parameters.Add("@EndDate", SqlDbType.Date).Value = dateTo.Value
cmd.Parameters.Add("@numRes", SqlDbType.VarChar).Value = "=> " + txtResultAbove.Text
If txtServiceCode.TextLength > 0 Then
cmd.Parameters.Add("@SvcAbb", SqlDbType.VarChar).Value = txtServiceCode.Text
Else
cmd.Parameters.Add("@SvcAbb", SqlDbType.VarChar).Value = "%"
End If
我以为这是我设置参数值的方式,然后我将“=>”移动到查询中,并将参数保留为仅 texbox 值:
...
WHERE rqs.number_result >= @numRes AND rq.entry_date BETWEEN @StartDate AND @EndDate AND svc.service_abbrev LIKE @SvcAbb
...
cmd.Parameters.Add("@numRes", SqlDbType.VarChar).Value = txtResultAbove.Text
...
然后我想,也许它需要是一个整数才能工作,所以我这样做了:
Convert.ToInt32(txtResultAbove.Text)
cmd.Parameters.Add("@numRes", SqlDbType.Int).Value = txtResultAbove.Text
那也没有用。
例外情况:
System.Data.SqlClient.SqlException:“>”附近的语法不正确。
我在这里做错了什么?如果我用静态字符串替换参数(即 >= 45),则查询有效
答:
1赞
Adrian Maxwell
10/27/2023
#1
在 SQL Server 中尝试以下操作:
select *, '>=' using
from (select 1 as col1) dummy
where col1 >= 0
;
该查询工作正常!现在运行这个:
select *, '=<' using
from (select 1 as col1) dummy
where col1 =< 0
;
第二个查询将重现错误消息。Incorrect syntax near '<'.
即不要使用=<
评论
0赞
Adrian Maxwell
10/27/2023
顺便说一句:我并不是主张你应该继续用“<=”连接一个数字,但我想我已经确定了你认为你需要这样做的原因。
评论
=>
应该是 是的,你不能把实际的代码,比如运算符放到参数中。>=
>=