过滤数据库中的多个列

时间:2017-06-02 09:51:20

标签: c# sql-server vba

  

COLUMNS employee_id,last_name,first_name,reporting_to,official_start_time,employee_status,dept_name

Private Sub btnSearch_Click(sender as Object,e As EventArgs)处理btnSearch.Click

Dim strSELECT As String = 
    "SELECT * FROM [TABLENAME]WHERE last_name LIKE '"     
    & tbxLastName.Text.ToString() 
    & "%' AND first_name LIKE'" & tbxFirstName.Text.ToString() & "%' AND reporting_to LIKE '" 
    & tbxReportingTo.Text 
    & "%' AND employee_status = '" 
    & cbxEmpStatus.Items(cbxEmpStatus.SelectedIndex) & "'AND dept_name ='" 
    & cbxDeptName.Items(cbxDeptName.SelectedIndex).ToString &"';"
End Sub

点击按钮搜索,我想用输入项过滤我的数据。

我遇到的问题是,如果我将一个文本框留空,则查询无法解决此问题。下面我将提供一些人建议的示例代码,但我不知道如何实现它。

Public Function ReadRecords(ByVal strTblName As String,
    ByVal strColumns As String,
    ByVal strFilter As String,
    ByVal strSortOrder As String) As DataTable

    Dim dtRecords As New DataTable
    Dim strSQL As String

    If strColumns = String.Empty Then
        strSQL = "SELECT * FROM " + strTblName
    Else
        strSQL = "SELECT " & strColumns & " FROM " + strTblName
    End If

    If strFilter <> String.Empty Then
        strSQL = strSQL + " WHERE " + strFilter
    End If
    If strSortOrder <> String.Empty Then
        strSQL = strSQL + " ORDER BY " + strSortOrder
    End If

    dtRecords = ExecQuery(strSQL)
    Return dtRecords
End Function

下面我有一张示例数据库的图片[不介意其中的列名]我希望能够过滤所有包含IT作为部门的记录,同时还要搜索姓氏的第一个字母让我们说W 所以我的查询输出应该是员工100 William ETC ......

enter image description here

2 个答案:

答案 0 :(得分:0)

公共函数ReadRecords(ByVal strTblName As String,                             ByVal strColumns As String,                             ByVal strFilter As String,                             ByVal strSortOrder As String)As DataTable

Dim dtRecords As New DataTable
Dim strSQL As String

If strColumns = String.Empty Then
    strSQL = "SELECT * FROM " + strTblName +" WHERE " 
Else
    strSQL = "SELECT " & strColumns & " FROM " + strTblName +" WHERE " 
End If

If strFilter <> String.Empty Then
    strSQL = strSQL + + strFilter
End If
If strSortOrder <> String.Empty Then
    strSQL = strSQL + strSortOrder
End If

dtRecords = ExecQuery(strSQL)
Return dtRecords

结束功能

你必须在if语句之前添加WHERE Con​​dition, 更新了您的代码,请测试一下。

答案 1 :(得分:0)

如果我没有弄错的话,您只需要使用%运算符和LIKE关键字。 您的查询应该看起来像SELECT * FROM tableName WHERE columnName LIKE condition + %