我想知道vb.net中sql通配符表达式的正确语法是什么
我想要的是当我的dayVariable与Day记录匹配时选择我的记录,如果我的dayVariable =“T”则示例,那么我的sql表达式需要显示Day中具有字母“T”甚至“TF”的所有记录或“FT”,只要有“T”
我只尝试显示记录哪一天与“T”完全匹配的记录
SELECT * FROM tblSomething WHERE Day LIKE '%" + dayVariable + "%'
SELECT * FROM tblSomething WHERE Day LIKE '%" & dayVariable & "%'
注意:我尝试在sql express中构建查询,如下所示:
SELECT * FROM tblSomething WHERE Day LIKE '%T%'
我实现了显示Day列中包含“T”字母的所有记录。
这是我真实的Vb.net
Private Function checkSecConflict(ByVal sTime As String, ByVal eTime As String, ByVal secID As String, ByVal day As String) As Boolean
If Connect.State = ConnectionState.Closed Then
Connect.Open()
End If
Dim cmd2 As New SqlCommand("Select * from tblSubjectOffer Where eTime > " & sTime & " AND sTime < " & eTime & " AND Day LIKE '%' + day + '%' AND SectionID = '" & secID & "'", Connect)
Dim dr As SqlDataReader = cmd2.ExecuteReader()
dr.Read()
If dr.HasRows Then
Return True
Else
Return False
End If
dr.Close()
cmd2.Dispose()
End Function
只是忽略我关于时间和secID的where语句,因为我发现我的关于日的通配符是真正的问题,我想是这样的,:))
提前感谢那些想帮助我解决问题的人,
答案 0 :(得分:0)
" AND Day LIKE '%' + day + '%' AND SectionID = '"
这应该是:" AND Day LIKE '%" + day + "%' AND SectionID = '"
您没有正确地将day
参数附加到字符串中。
答案 1 :(得分:0)
您的代码存在一些需要修复的问题 首先,不要使用全局Sql连接。有connection pooling机制允许快速创建和打开连接。
其次,使用参数化查询将值传递给数据库引擎,为数据库列指定正确的数据类型。允许自动解释字符串值会导致错误,并使用Sql Injection
使您的代码易于利用最后,每个一次性对象(如连接,命令和阅读器)都应该包含在Using Statement中,该{{3}}提供关闭和处理这些对象的正确功能(在例外情况下也是如此)
Private Function checkSecConflict(ByVal sTime As String, ByVal eTime As String, ByVal secID As String, ByVal day As String) As Boolean
Dim sqlText = "Select * from tblSubjectOffer " & _
"Where eTime > @starttime AND sTime < @endtime AND " & _
"Day LIKE @day AND SectionID = @secid"
Using con = new SqlConnection(....connection string here ....)
Using cmd2 As New SqlCommand(sqlText, con)
con.Open()
cmd.Parameters.Add("@starttime", SqlDbType.DateTime).Value = Convert.ToDateTime(eTime)
cmd.Parameters.Add("@endttime", SqlDbType.DateTime).Value = Convert.ToDateTime(sTime)
cmd.Parameters.Add("@day", SqlDbType.NVarChar).Value = "%" & day & "%"
cmd.Parameters.Add("@secid", SqlDbType.Int).Value = Convert.ToInt32(secID)
Using dr = cmd2.ExecuteReader()
' the value True/False of HasRows could be used as return here
return dr.HasRows
End Using
End Using
End Using
End Function
注意:此代码假定您的字段eTime
和sTime
为smalldatetime
(或类似字段),字段Day
为nvarchar
且{ {1}}是SectionID
答案 2 :(得分:0)
我总是使用... Day LIKE '*" + day + "*' ...
,似乎工作正常。