Problems with Database Search Code (asp.net vb)

Posted by Phil on Stack Overflow See other posts from Stack Overflow or by Phil
Published on 2010-03-26T07:15:51Z Indexed on 2010/03/26 7:33 UTC
Read the original article Hit count: 199

Filed under:
|
|

Here is a sample of my database search code:

Dim sql As String = "Select * From Table Where "

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

Dim andor As Boolean = AndOr1.SelectedValue 'selection can be AND or OR (0 / 1)

    'Code for when the user selects AND
            If NameSearch.Text.ToString IsNot String.Empty And andor = 0 Then
                sql += "Surname LIKE '%" & name & "%' AND "
            End If

            If EmailSearch.Text.ToString IsNot String.Empty And andor = 0 Then
                sql += "Email LIKE '%" & email & "%' AND "
            End If

            If CitySearchBox.Text.ToString IsNot String.Empty And andor = 0 Then
                sql += "City LIKE '%" & city & "%' AND "
            End If

'Code for when the user selects OR
        If NameSearch.Text.ToString IsNot String.Empty And andor = 1 Then
            sql += "(Surname LIKE '%" & name & "%' OR "
        End If

        If EmailSearch.Text.ToString IsNot String.Empty And andor = 1 Then
            sql += "Email LIKE '%" & email & "%') OR "
        End If

        If CitySearchBox.Text.ToString IsNot String.Empty And andor = 1 Then
            sql += "(City LIKE '%" & city & "%' OR "
        End If

sql = CleanString(sql)
End Sub

When the user selects AND (as andor.selectedvalue(0)) then the sql is produced fine like this;

Select * From Table Where Surname LIKE '%test%' AND Email LIKE '%test%' AND City LIKE '%test%' 

But if the user selects OR (as andor.selectedvalue(1)), nothing is outputted except;

Select * From Table Where 

Im sure the controls have values so are not string.empty and when the user selects OR the correct value 1 is being assigned to andor.

© Stack Overflow or respective owner

Related posts about dynamic-sql

Related posts about ASP.NET