Access and SQL date comparison - ms-access-2010

I have an Access 2010 front and sql2008 back. I am using a date parameter on a form and a view for the report. It doesn't give me any data. It's not understanding the access date paramter. I have tried converting the date in sql, but still no data. Here is the code I am using.
Private Sub Report_Open(Cancel As Integer)
LocationRpt
End Sub
Private Sub LocationRpt()
Dim frm As Form_frmSecRpt
Dim strSQL As String
Dim SchDt As Date
Set frm = Form_frmSecRpt
SchDt = frm.txtDate
strSQL = "Select * From vw_SecLocationWO Where ReSchDt =" & SchDt
Me.RecordSource = strSQL
End Sub

Access SQL expects date values to be delimited with hash marks (#), so try this instead:
strSQL = "SELECT * FROM vw_SecLocationWO WHERE ReSchDt = #" & Format(SchDt, "yyyy-mm-dd") & "#"

Related

Delete file from server based on database query asp.net vb

I have a file folder that contains pdf files. The sql database is not directly related to the files. For example, I have "Invoice_co_355_24636.pdf" and "Invoice_co_355_25127.pdf" in the Invoices folder. I query the database and find that Invoice "24636" is not paid and "25127" is marked paid in full, so I would like to delete "Invoice_co_355_25127.pdf" at that point since it is paid.
So what I'm doing is getting all the file names from the folder, parsing each file to get just the last numbers, (which correlate to the database). If the database shows that one or more of the Invoices has been paid, I would like to delete the file.
I have successfully, (below), been able to parse the server file names as
"InvNo" as the parsed file name, (which corelates to the database), and
"InvNoFull", which is the full database file name that needs to be deleted if it is marked as paid in the database.
But after getting the file names and the parsed file names, I do not know how to actually compare it to the database and then delete. Any help is appreciated.
Dim files() As String = Directory.GetFiles(Server.MapPath("/Contents/Invoices/" + Variable.ToString() + "/Co/" + ddlCo.SelectedValue.ToString() + "/"))
For Each file As String In files
Dim InvNo As String = Path.GetFileNameWithoutExtension(file)
Dim InvNoFull As String = Path.GetFileName(file)
InvNo = InvNo.Substring(InvNo.LastIndexOf("_") + 1, InvNo.Length - InvNo.LastIndexOf("_") - 1)
Dim CnStr As String = (ConfigurationManager.ConnectionStrings("ClientConnectionString").ConnectionString)
Dim adp As SqlDataAdapter = New SqlDataAdapter("select OrderBilling.OrderId from orderBilling Left Outer Join Orders on OrderBilling.OrderId = Orders.OrderId Where Orders.CompanyId = " & ddlCo.SelectedValue.ToString() & " And Orders.OwnerId = " & Variable.ToString() & " And OrderBilling.PaidInFull = 'False'", CnStr)
Dim ds As DataSet = New DataSet()
adp.Fill(ds, "outBill")
For Each Row As DataRow In ds.Tables(0).Rows
For Each Coll As DataColumn In ds.Tables(0).Columns
Dim s As String = Row(Coll.ColumnName).ToString()
If s <> InvNo Then
Dim FileToDelete() As String
FileToDelete = Directory.GetFiles(Server.MapPath("/Contents/Invoices/" + Variable.ToString() + "/Co/" + ddlCo.SelectedValue.ToString() + "/" + InvNoFull))
If System.IO.File.Exists(FileToDelete.ToString()) = True Then
System.IO.File.Delete(FileToDelete.ToString())
'MsgBox("File Deleted")
End If
End If
Next
Next
Next
With help from Mary but this deletes all the files in the folder, but I want it to delete only the files not returned in the database query:
Private Sub DeletePaidInvoices(OwnerID2 As String, CompanyID As String)
Dim InvoicePath = "/Contents/Invoices/" & OwnerID2 & "/Co/" & CompanyID & "/"
Dim files() As String = Directory.GetFiles(Server.MapPath(InvoicePath))
Dim lst = GetInvoiceInfo(CInt(CompanyID), CInt(OwnerID2))
For Each file As String In files
Dim InvNo As String = Path.GetFileNameWithoutExtension(file)
Dim InvNoFull As String = Path.GetFileName(file)
InvNo = InvNo.Substring(InvNo.LastIndexOf("_") + 1, InvNo.Length - InvNo.LastIndexOf("_") - 1)
'Debug.Print(InvNo) 'To check your substring, will not be in release version
For Each i As Integer In lst
Dim s As String = i.ToString()
If s <> InvNo Then
Dim FileToDelete As String
FileToDelete = "Invoice_co_" & CompanyID & "_" & InvNo & ".pdf"
If System.IO.File.Exists(Server.MapPath(InvoicePath & FileToDelete.ToString())) = True Then
System.IO.File.Delete(Server.MapPath(InvoicePath & FileToDelete.ToString()))
End If
End If
Next
Next
End Sub
Call your delete method from, say, a button passing the variable from the user interface.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim CompID = ddlCo.SelectedValue.ToString()
Dim OwnerID = "comes from somewhere"
DeletePaidInvoices(OwnerID, CompID)
End Sub
The delete method gets the file list. I have no idea about Server.MapPath but I assume you do. Next we get a List(Of Integer) representing the results of you database query (the OrderID's). Next we enter the For loop. I added a Debug line to see what is being returned by SubString code. As you can see it is simpler code to loop through a list.
Private Sub DeletePaidInvoices(OwnerID As String, CompanyID As String)
Dim InvoicePath = $"/Contents/Invoices/{OwnerID}/Co/{CompanyID}/"
Dim files() As String = Directory.GetFiles(Server.MapPath(InvoicePath))
Dim lst = GetInvoiceInfo(CInt(CompanyID), CInt(OwnerID))
For Each file As String In files
Dim InvNo As String = Path.GetFileNameWithoutExtension(file)
Dim InvNoFull As String = Path.GetFileName(file)
InvNo = InvNo.Substring(InvNo.LastIndexOf("_") + 1, InvNo.Length - InvNo.LastIndexOf("_") - 1)
Debug.Print(InvNo) 'To check your substring, will not be in release version
For Each i As Integer In lst
Dim s As String = i.ToString()
If s <> InvNo Then
Dim FileToDelete() As String
FileToDelete = Directory.GetFiles(Server.MapPath(InvoicePath & InvNoFull))
If System.IO.File.Exists(FileToDelete.ToString()) = True Then
System.IO.File.Delete(FileToDelete.ToString())
'MsgBox("File Deleted")
End If
End If
Next
Next
End Sub
The data retrieval is in a separate function. Use Using blocks to make sure your connections and commands are closed and disposed. Always use parameters with Sql Server. There is a bit of Linq magic at the end to create the list from the DataTable.
Private Function GetInvoiceInfo(CompanyID As Integer, OwnerID As Integer) As List(Of Integer)
Dim dt As New DataTable
Using cn As New SqlConnection(ConfigurationManager.ConnectionStrings("ClientConnectionString").ConnectionString),
cmd As New SqlCommand("select OrderBilling.OrderId
from orderBilling
Left Outer Join Orders on OrderBilling.OrderId = Orders.OrderId
Where Orders.CompanyId = #CompanyID
And Orders.OwnerId = #OwnerID
And OrderBilling.PaidInFull = #Paid;", cn)
cmd.Parameters.Add("#CompanyID", SqlDbType.Int).Value = CompanyID
cmd.Parameters.Add("#OwnerID", SqlDbType.Int).Value = OwnerID
cmd.Parameters.Add("#Paid", SqlDbType.Bit).Value = False
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
Dim lstOrderID As List(Of Integer) = (From dRow In dt.AsEnumerable() Select dRow.Field(Of Integer)(0)).ToList
Return lstOrderID
End Function
The actual deleting of the files (or moving to a Paid folder) is up to you.

Using parameterized query is causing data type mismatch. Any ideas?

I have a dropdownList with control ID of HourlyCharter.
Then on codebehind, I am trying to query records from the database where hourly is equal to the value of HourlyCharter.
If I use this code:
StrSQL = "select h.fare, h.tip, h.total from hourlyQRY h "
StrSQL += " Where h.Hourly = " & HourlyCharter.SelectedValue
' Initialize Database Connection
Dim connStr As String = ConfigurationManager.ConnectionStrings("ALSConnectionString").ConnectionString
Dim conn As New OleDbConnection(connStr)
Dim cmd As New OleDbCommand(StrSQL, conn)
It works.
If I use parameterized query such as this:
StrSQL = "select h.fare, h.tip, h.total from hourlyQRY h "
StrSQL += " Where h.Hourly = #hourly"
' Initialize Database Connection
Dim connStr As String = ConfigurationManager.ConnectionStrings("ALSConnectionString").ConnectionString
Dim conn As New OleDbConnection(connStr)
Dim cmd As New OleDbCommand(StrSQL, conn)
'We use parametized query to prevent sql injection attack
Dim p1 As New OleDbParameter("#hourly", HourlyCharter.SelectedValue)
cmd.Parameters.Add(p1)
I get following error:
Data type mismatch in criteria expression
Hourly is of Number data type and we are using Access 2010 database.
Any ideas how to resolve this?
'open recordset to receive db values
rs = cmd.ExecuteReader()
' This acts like the (Not RecordSource.Eof) in ASP 3.0 to loop and retrieve records.
While rs.Read()
' If rs("city") <> "" Then
Dim tipValue As Decimal = rs("tip")
Dim totValue = rs("total")
' Else
' End If
Dim tp As String = [String].Format("{0:C}", tipValue)
Dim tot As String = [String].Format("{0:C}", totValue)
lblTip.Text = tp
lblTotal.Text = tot
End While
You need to make sure the object you put in the parameter is also a numeric type. SelectedValue is a string.
Dim p1 As New OleDbParameter("#hourly", Decimal.Parse(HourlyCharter.SelectedValue))
That's where the data type mismatch happens - it's expecting a number but it's getting a string.
Instead of
Dim p1 As New OleDbParameter("#hourly", HourlyCharter.SelectedValue)
cmd.Parameters.Add(p1)
You can try
cmd.Parameters.AddWithValue("#hourly", HourlyCharter.SelectedValue)
Try specifying the datat type of the parameter. You can do it after creating it:
p1.OleDbType = OleDb.OleDbType.Numeric
You can also do it on the constructor, but it requires a lot more parameters and I'm not sure you have all those nor I do know what they do.

Update SQL Server tables using textboxes

I'm programming an education website using asp.net vb.net and SQL Server. I have 4 stackholders, if any body log in in his profile he will see his information
If he wants to update them he just change the textboxes then click update
My problem is how to update.
I wrote a method to update but it always show me a syntax error in the query. I made sure there is no problem. I'm updating two tables and I made to sql statements!
My qustion is can I Insert instead of update?
If not: how to upade one record based on the session I have?
please help me
this my code
' Private Sub UpdateInfo(ByVal USER_ID As Integer)
'Dim User As Integer = USER_ID
'Dim sql1 As String = "UPDATE AdminCoordinatorInformation SET MobileNumber =" + tbmobile.Text + ", HomeNumber=" + tbhome.Text + ", AltRelation = " + DDLRelationShip.SelectedValue + ", AlTitle = " + DDLTitle.SelectedValue + ", AltName = " + tbemname.Text + ", AltMobile = " + tbemmobile.Text + " WHERE USER_ID = User)"
'Dim sql2 As String = "UPDATE DIP_USERS SET USER_Email=" + tbEmail.Text.Trim + " WHERE USER_ID = User)"
' Try
' Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("mydbConnectionString").ConnectionString)
' Dim cmd1 As New SqlCommand(sql1, conn)
' Dim cmd2 As New SqlCommand(sql2, conn)
' cmd2.Parameters.AddWithValue("#FirstName", tbname.Text)
' cmd2.Parameters.AddWithValue("#USER_PASSWORD", tbnewpassword.Text)
' cmd2.Parameters.AddWithValue("#USER_Email", tbEmail.Text)
' cmd1.Parameters.AddWithValue("#MobileNumber", tbmobile.Text)
' cmd1.Parameters.AddWithValue("#HomeNumber", tbhome.Text)
' cmd1.Parameters.AddWithValue("#AltRelation", DDLRelationShip.SelectedValue)
' cmd1.Parameters.AddWithValue("#AlTitle", DDLTitle.SelectedValue)
' cmd1.Parameters.AddWithValue("#AltName", tbemname.Text)
' cmd1.Parameters.AddWithValue("#AltMobile", tbemmobile.Text)
' conn.Open()
'Dim ra As Integer = cmd1.ExecuteNonQuery()
'Dim ra1 As Integer = cmd2.ExecuteNonQuery()
'cmd1.Dispose()
'cmd2.Dispose()
' conn.Close()
' Catch ex As Exception
' MsgBox(ex.Message)
' End Try
'End Sub
you have not specified your parameters in your query, you're directly concatenating the values of controls inside your query. And still you have added parameters.
Firstly, do not concatenate your sql query like that, its prone to SQL Injection.
construct your query like this:
Dim sql1 As String = "UPDATE AdminCoordinatorInformation SET
MobileNumber =#MobileNumber,
HomeNumber=#HomeNumber,
AltRelation = #AltRelation,
AlTitle = #AlTitle,
AltName =#AltName,
AltMobile = #AltMobile
WHERE USER_ID = #User"
Dim sql2 As String = "UPDATE DIP_USERS SET
USER_Email=#USER_Email
WHERE USER_ID = #User"
and also, add this parameter too
cmd1.Parameters.AddWithValue("#User", USER_ID)
cmd2.Parameters.AddWithValue("#User", USER_ID)
And one very important thing. you need to assign proper datatype to your columns in the query i.e.
remember these things.
txtBox.Text returns String value, you might need to convert it to Int32 using Convert.Int32 or you need to wrap it in single quote, based totally upon datatype of your column
Put parameters which you declare in your SQL Command query:
"UPDATE AdminCoordinatorInformation SET MobileNumber=#MobileNumber,HomeNumber=#homeNumber...
You get syntax error because your string data in sql query must be wrapped with "'".
"UPDATE AdminCoordinatorInformation SET MobileNumber='0987654321',....
Note: creating sql queries by concating query with user inputs ("...SET MobileNumber='" + txtbox.Text + "',...") is not good/dangerous practice because of SQL Injection

Getting row Count only returns value of 1

I am using Sql Server 2005 and Vb Studios 2010 on a .net Framework of 4.0. I am trying to get the exact number of rows from a database and populate a datatable then have a label show the number of rows.
Dim comm2 = db.selectcommand(db.conn, "*", "Tablename", " columnname = '" & Session(sessionvariable) & "' AND columnname = 'Unread '")
Dim sqlda2 As New SqlDataAdapter(comm2)
Dim dt2 As New DataTable
sqlda2.Fill(dt2)
Dim recordcount As Integer = dt2.Rows.Count
messagecountlbl.Text = recordcount
this will always return the value of 1 and I know for a fact that I have multiple values for the data I am trying to pull. I have atleast 50 and the label should be displaying that amount.
I have also tried the Select Count statement and it does the same thing.
Fix I have added this to the post since there is a 24 hr wait to answer question:
I have found a quick and simple fix that I will shorten later in a class file that I have written but this should help alot of people out.
Dim sqlresult As Object
Dim constring As String = "Connection string goes here"
Dim dbcon As SqlConnection = New SqlConnection(constring)
Dim sql As New SqlCommand
dbcon.Open()
sql.Connection = dbcon
sql.CommandText = "SELECT COUNT (*) FROM Tablename WHERE Columnname = 'Unread' AND columnname = '" & Session("sessionvariable") & "'"
sqlresult = sql.ExecuteScalar
messagecountlbl.Text = sqlresult
Aren't you missing quotes around Unread?
Also... you're susceptible to SQL Injection. Use Parameters instead
Also... if all you are doing is getting the number of rows, your code is overkill
I just noticed.... you Dimmed comm2 but your adapter uses comm
Your updated question was the route that I would have gone. This was why i said your initial code was overkill (in terms of memory usage...). DataAdapters and DataTables for one value is in no way efficient.
You might want to change your updated code to the following...
Again, look up SQL Injection to see why you should never (or at least try not to) build a sql string like that
Dim sqlresult As Object
Dim constring As String = "Connection string goes here"
Dim dbcon As SqlConnection = New SqlConnection(constring)
Dim sql As New SqlCommand
dbcon.Open()
sql.Connection = dbcon
sql.CommandText = "SELECT COUNT (*) FROM Tablename WHERE Columnname = 'Unread' AND columnname = #param"
sql.Parameters.AddWithValue("#param", Session("sessionvariable"))
sqlresult = sql.ExecuteScalar
messagecountlbl.Text = sqlresult
It looks like you're missing a single quote at the beginning of the word "Unread".
...& "' AND columnname = 'Unread'")
I note that your first line declares a variable called comm2 but you don't use it later - instead you're using simply comm.
With that in mind, the fact that you've omitted the quotes around Unread will still be relevant.
Fix I have added this to the post since there is a 24 hr wait to answer question: I have found a quick and simple fix that I will shorten later in a class file that I have written but this should help alot of people out.
Dim sqlresult As Object
Dim constring As String = "Connection string goes here"
Dim dbcon As SqlConnection = New SqlConnection(constring)
Dim sql As New SqlCommand
dbcon.Open()
sql.Connection = dbcon
sql.CommandText = "SELECT COUNT (*) FROM Tablename WHERE Columnname = 'Unread' AND columnname = '" & Session("sessionvariable") & "'"
sqlresult = sql.ExecuteScalar
messagecountlbl.Text = sqlresult

An example of advanced database search

im looking for an example script. I saw one yesterday but for the life of me I can't find it again today.
The task I have is to allow the user to search 1 database table via input controls on an aspx page where they can select and , or , equals to combine fields, generating the sql on the fly with concat/stringbuilder or similar. (it runs behind the corp firewall)
Please can someone point me in the right direction of an example or tutorial
I've been working on the page, but have run into problems. Here is the Page_load;
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim sql As String = ("Select * From Table Where ")
'variables to hold the and or values between fields
Dim andor1v As String = AndOr1.SelectedValue.ToString()
Dim andor2v As String = AndOr2.SelectedValue.ToString()
Dim andor3v As String = AndOr3.SelectedValue.ToString()
Dim andor4v As String = AndOr4.SelectedValue.ToString()
Dim andor5v As String = AndOr5.SelectedValue.ToString()
Dim andor6v As String = AndOr6.SelectedValue.ToString()
'variables to stop web control inputs going direct to sql
Dim name As String = NameSearch.Text.ToString()
Dim email As String = EmailSearch.Text.ToString()
Dim city As String = CitySearchBox.Text.ToString()
Dim province As String = ProvinceSelect.SelectedValue.ToString()
Dim qualifications As String = QualificationsObtained.Text.ToString()
Dim competencies As String = CompetenciesDD.SelectedValue.ToString()
Dim expertise As String = Expertiselist.SelectedValue.ToString()
If NameSearch.Text IsNot String.Empty Then
sql += "Surname LIKE '%" & name & "%' "
End If
If EmailSearch.Text IsNot String.Empty Then
sql += andor1v & " Email LIKE '%" & email & "%' "
End If
If CitySearchBox.Text IsNot String.Empty Then
sql += andor2v & " City LIKE '%" & city & "%' "
End If
If QualificationsObtained.Text IsNot String.Empty Then
sql += andor3v & " (institutionquals1 LIKE '%" & qualifications & "%') OR " & _
"(institutionquals2 LIKE '%" & qualifications & "%') OR " & _
"(institutionquals3 LIKE '%" & qualifications & "%') OR " & _
"(institutionquals4 LIKE '%" & qualifications & "%') "
End If
Dim selectedrow As String = CompetenciesDD.SelectedValue.ToString
Dim selectedquals As String = NQFlevel.SelectedValue.ToString
If CompetenciesDD.SelectedValue.ToString IsNot "0" And selectedquals = 0 Then
sql += (selectedrow & " = 1 ")
ElseIf selectedrow = "assessortrue" And selectedquals IsNot "0" Then
sql += andor4v & (" assessortrue=1 and assessorlvl=" & selectedquals)
ElseIf selectedrow = "coordinatortrue" And selectedquals IsNot "0" Then
sql += andor4v & ("coordinatortrue=1 and coordinatorlvl=" & selectedquals)
ElseIf selectedrow = "facilitatortrue" And selectedquals IsNot "0" Then
sql += andor4v & ("facilitatortrue=1 and facilitatorlvl=" & selectedquals)
ElseIf selectedrow = "moderatortrue" And selectedquals IsNot "0" Then
sql += andor4v & ("moderatortrue=1 and moderatorlvl=" & selectedquals)
ElseIf selectedrow = "productdevelopertrue" And selectedquals IsNot "0" Then
sql += andor4v & ("productdevelopertrue=1 and productdeveloperlvl=" & selectedquals)
ElseIf selectedrow = "projectmanagertrue" And selectedquals IsNot "0" Then
sql += andor4v & ("projectmanagertrue=1 and projectmanagerlvl=" & selectedquals)
End If
Response.Write(sql)
End Sub
After an hours tinkering the code is now looking as it does above ^
Now the problem im faced with is if a user does not enter a value for surname (the first field) but does enter a value for email (or any subsequent fields), the sql produced has an extra and like this;
Select * From Table Where And Email LIKE '%test%'
I'm also looking for a way to take the OR option into account. Do you think this should be done as Martin says where the whole query is either an and or an or and not a mix of the 2? Then I should be able to take out all the and/or drop downs?
Thanks.
NB: I'm not really looking for comments on how I should parameterise or about sql injection.
Regarding your issue with users not selecting an option you could just remove the "please select" and have it default to "and"
Also what is the desired behaviour if they select a mix of ANDs and ORs?
By default the ANDs will be evaluated first in the absence of any brackets
http://msdn.microsoft.com/en-us/library/ms186992.aspx
So if they enter
name="Fred" or email="blah" and
city="london" and province="xyz" or
qualifications="Degree"
I'm not really sure what the desired semantics would be?
Is it
(name="Fred" or email="blah") and
city="london" and (province="xyz" or
qualifications="Degree")
or
(name="Fred" or (email="blah" and
city="london") and province="xyz") or
qualifications="Degree"
Or something different? Maybe you should restrict them to AND or OR for the whole query or allow them to disambiguate either by typing in advanced search syntax with brackets or by providing a query builder UI.
To avoid sql injection and allow a dynamic search I would probably write a stored procedure something like this. If nothing is selected send DBNull.Value in the ado.net parameters collection as the parameter value. With this approach you can check any columns you want and if they are not selected by the user they will be ignored.
EDIT: I just saw that you are not allowed to use stored procedures. I changed my answer below to show a parameterized sql statement
SELECT * FROM TABLE
WHERE ([name] = #name OR #name IS NULL)
AND (email = #email OR #email IS NULL)
AND (city = #city OR #city IS NULL)
AND (province = #province OR #province IS NULL)
AND (qualifications = #qualifications OR #qualifications IS NULL)
AND (competencies = #competencies OR #competencies IS NULL)
AND (expertise = #expertise OR #expertise IS NULL)
Concat strings to build a query is never a good idea. You should use a stored procedure or parametrized queries
I have done this "dynamic" type query interface on classic asp.
The advice that I give to you is that you are trying to do the whole query in one page load so...
Look to "building" the query via a "wizard" type interface - either ajax for the newness or simple multiple pages for each part of the query building.
This is essence gives you "persitance" via what ever means you have (session, dbstore, cookie etc) for each part of the query and you have can sanity check each part of the query as you build.
Dim sql As String = ("Select * From Table Where **1=1**")
'variables to hold the and or values between fields
Dim andor1v As String = AndOr1.SelectedValue.ToString()
Dim andor2v As String = AndOr2.SelectedValue.ToString()
Dim andor3v As String = AndOr3.SelectedValue.ToString()
Dim andor4v As String = AndOr4.SelectedValue.ToString()
Dim andor5v As String = AndOr5.SelectedValue.ToString()
Dim andor6v As String = AndOr6.SelectedValue.ToString()
'variables to stop web control inputs going direct to sql
Dim name As String = NameSearch.Text.ToString()
Dim email As String = EmailSearch.Text.ToString()
Dim city As String = CitySearchBox.Text.ToString()
Dim province As String = ProvinceSelect.SelectedValue.ToString()
Dim qualifications As String = QualificationsObtained.Text.ToString()
Dim competencies As String = CompetenciesDD.SelectedValue.ToString()
Dim expertise As String = Expertiselist.SelectedValue.ToString()
If NameSearch.Text IsNot String.Empty And andor1v IsNot "0" Then
sql += "**and** Surname LIKE '%" & name & "%' "
ElseIf NameSearch.Text IsNot String.Empty And andor1v Is "0" Then
sql += "**or** Surname LIKE '%" & name & "%' "
End If
....additional logic here.....
Response.Write(sql)
End Sub
note the ** parts. 1=1 evaluates to true on most DBMS. This allows you to just start concatenating your or / ands on to it without worrying about ()'s

Resources