使用SQL根据用户输入搜索数据库中的子字符串

时间:2012-11-20 16:03:20

标签: sql vb.net visual-studio-2010 string-matching sql-like

我正在做一个uni项目,我需要在Visual Studio 2010中从数据库中搜索用户,使用vb.net中的SQL命令,根据他们的FirstName,SurName,EmailAddress或SkillSet。

所以从一开始......使用注册并包含一个技能组,它是一个单独的文本框,用“Java”,“C#”等类型输入。

如果用户有多种技能,我可以搜索除SkillSet之外的所有内容。

我想在SQL命令中使用“LIKE”搜索任何内容。

以下是我在搜索用户时所拥有的内容:

用于选择所需详细信息的SQL命令

Dim command As New SqlCommand("SELECT [FirstName], [SurName], [EmailAddress], [SkillSet], [UserID] FROM [Users] WHERE ([FirstName] = @FirstName OR [SurName] = @SurName OR [EmailAddress] = @EmailAddress OR [SkillSet] LIKE '%' @SkillSet '%')", connection)

创建参数

    Dim firstnameParam As New SqlParameter("@FirstName", Me.UserSearchTextBox.Text)
    Dim surnameParam As New SqlParameter("@SurName", Me.UserSearchTextBox.Text)
    Dim emailParam As New SqlParameter("@EmailAddress", Me.UserSearchTextBox.Text)
    Dim skillSetParam As New SqlParameter("@SkillSet", Me.UserSearchTextBox.Text)

    command.Parameters.Add(firstnameParam)
    command.Parameters.Add(surnameParam)
    command.Parameters.Add(emailParam)
    command.Parameters.Add(skillSetParam)`

3 个答案:

答案 0 :(得分:1)

而不是LIKE你想要使用IN

Dim command As New SqlCommand("SELECT [FirstName], [SurName], [EmailAddress], [SkillSet], [UserID] FROM [Users] WHERE ([FirstName] = @FirstName OR [SurName] = @SurName OR [EmailAddress] = @EmailAddress OR [SkillSet] IN (@SkillSet)", connection)

需要以诸如

之类的格式传递SkillSet
'SQL','PHP','JAVA'

我不太了解Vb.net,建议将用户输入格式化为所需的字符串。

答案 1 :(得分:0)

一个非常快的谷歌在这个网站上揭示了以下答案:

Use of SqlParameter in SQL LIKE clause not working

Howto? Parameters and LIKE statement SQL

所以很简单,您需要使用&(因为您在VB.NET中 - 这将是C#.NET中的+)将字符串'%'与参数连接起来,像这样:

Dim command As New SqlCommand("SELECT [FirstName], [SurName], [EmailAddress], [SkillSet], [UserID] FROM [Users] WHERE ([FirstName] = @FirstName OR [SurName] = @SurName OR [EmailAddress] = @EmailAddress OR [SkillSet] LIKE '%' & @SkillSet & '%')", connection)

Dim skillSetParam As New SqlParameter("@SkillSet", "%" & Me.UserSearchTextBox.Text & "%")

从查询中删除'%'会产生相同的结果。

答案 2 :(得分:0)

现在就开始工作了。我错过了另一组括号。现在,如果用户只插入了几个字符,我就可以检索结果。谢谢你们的帮助!!

Dim command As New SqlCommand("SELECT [FirstName], [SurName], [EmailAddress], [UserID], [SkillSet] FROM [Users] WHERE ([FirstName] = @FirstName OR [SurName] = @SurName OR [EmailAddress] = @EmailAddress OR [SkillSet] LIKE '%@SkillSet%' )", connection)