VBscript/SQL concatenation of % - sql

Ok, I am new to the forum and fairly new to coding, I've searched high and low, and I understand that vbscript requires escapes or Chr() to use special characters. In the following code I need to concatenate a '%' after the "doc_no" as a wildcard for a sybase database to pull up the list of document numbers that I need to appear in my table.
I have tried
' " & doc_no " ' & Chr(37) " 'this returned that "&" is an invalid character
' " & doc_no " ' || Chr(37) "
' " & doc_no " ' + ""%"" " returned + as an invalid character
I have tried several variations of each type, and I cannot find any similar situation online. Any advice? Again, I am only 4 months into my programming life so bear with me please. Below is a snippet of the code from which the above originates.
<%
Dim document(1024)
counter = 0
cmdString = ""
cmdString = cmdString & "SELECT dbo.dsk_obj.obj_id,"
cmdString = cmdString & " docno = dbo.dsk_obj.obj_usr_num "
cmdString = cmdString & "FROM dbo.dsk_obj "
cmdString = cmdString & "WHERE dbo.dsk_obj.obj_usr_num LIKE '" & doc_no & "' I NEED TO CONCAT. % HERE "
objRS.Open cmdString, objConn, adOpenStatic, 3, adCmdText
WHILE (objRS.EOF = False)
document(counter) = objRS("docno")
counter = counter + 1
objRS.MoveNext
WEND
objRS.Close
%>
<% FOR ii = 0 TO counter -1 %>
<%=document(ii)%>
<%
NEXT
%>
the output should look something like this
1555307375-0001
1555307375-0002
1555307375-0003
Any help would be greatly appreciated! Thanks! Jeremy

First, you should avoid string concatenation because of SQL injection.
Now what you are trying to do is to create a SQL string in VBScript. The SQL you desire looks something like:
LIKE '123%'
To create this, you need a string in VBScript like:
Dim string = "LIKE '123%'"
To change out 123 for your doc number, you can do:
Dim string = "LIKE '" & doc_no & "123%'"
In your case, it would be:
cmdString = cmdString & "WHERE dbo.dsk_obj.obj_usr_num LIKE '" & doc_no & "%'"
But please don't do this. You should pass the parameter in instead of using string concatenation.

Related

Two combo values into sql string

I am trying to combine two combobox selected values in a sql string with the following code :
opdragplaasnommer.CommandText = "SELECT plaasnommer FROM oesskattings
WHERE plaasnaam = '" & CmbPlaasnaam.Text & "'" And aliasnaam = " '" &
CmbAliasnaam.Text & "'"
However, I think I am messing up with my quotes and double quotes. I get the following error message :
Additional information: Conversion from string "SELECT plaasnommer
FROM oesskatt" to type 'Boolean' is not valid.
You really ought to learn how to use the String.Format method or string interpolation. It is far less error-prone than using the concatenation operator (&) over and over. You can see the issue with your code simply by looking at the colour. Anything in a literal String should be red and you can see some of yours that should be red but isn't. Presumably it should be something like this:
opdragplaasnommer.CommandText = "SELECT plaasnommer FROM oesskattings WHERE plaasnaam = '" & CmbPlaasnaam.Text & "' And aliasnaam = '" & CmbAliasnaam.Text & "'"
Using String.Format would look like this:
opdragplaasnommer.CommandText = String.Format("SELECT plaasnommer FROM oesskattings WHERE plaasnaam = '{0}' And aliasnaam = '{1}'", CmbPlaasnaam.Text, CmbAliasnaam.Text)
As you can see, far less easy to mess up. String interpolation would look like this:
opdragplaasnommer.CommandText = $"SELECT plaasnommer FROM oesskattings WHERE plaasnaam = '{CmbPlaasnaam.Text}' And aliasnaam = '{CmbAliasnaam.Text}'"
Given that this is SQL code, an even better idea would be to use parameters. I'm not going to go into detail about that because there's information all over the place but it's something that you really need to learn. Apart from your code being less error-prone, it will help avoid crashes due to formatting issues and, most importantly, protect you from SQL injection attacks.
You have messed up with your string;
opdragplaasnommer.CommandText = "SELECT plaasnommer FROM oesskattings WHERE plaasnaam = '" & CmbPlaasnaam.Text & "' And aliasnaam = '" & CmbAliasnaam.Text & "'"
In VB .NET string concatination is performed with & symbol. And new line requires underscore.
opdragplaasnommer.CommandText = "SELECT plaasnommer FROM oesskattings" & _
" WHERE plaasnaam = '" & CmbPlaasnaam.Text & "' And aliasnaam = '" & _
CmbAliasnaam.Text & "'"
But I would suggest to use String.Format function in this case.
opdragplaasnommer.CommandText = String.Format("SELECT plaasnommer FROM oesskattings WHERE plaasnaam = '{0}' and aliasnaam = '{1}'",
CmbPlaasnaam.Text,CmbAliasnaam.Text)
And again this just another way. But, to say the truth, I hate concatination for SQL queries. Better to declare SQL Parameters and assign value to them.

Adding SQL to VBA in Access

I have the following SQL code:
SELECT GrantInformation.GrantRefNumber, GrantInformation.GrantTitle, GrantInformation.StatusGeneral, GrantSummary.Summary
FROM GrantInformation LEFT JOIN GrantSummary ON GrantInformation.GrantRefNumber = GrantSummary.GrantRefNumber
WHERE (((GrantInformation.LeadJointFunder) = "Global Challenges Research Fund")) Or (((GrantInformation.Call) = "AMR large collab"))
GROUP BY GrantInformation.GrantRefNumber, GrantInformation.GrantTitle, GrantInformation.StatusGeneral, GrantSummary.Summary
HAVING (((GrantSummary.Summary) Like ""*" & strsearch & "*"")) OR (((GrantSummary.Summary) Like ""*" & strsearch & "*""));
Which I want to insert into the following VBA:
Private Sub Command12_Click()
strsearch = Me.Text13.Value
Task =
Me.RecordSource = Task
End Sub
After 'Task ='.
However it keeps on returning a compile error, expects end of statement and half the SQL is in red. I have tried adding ' & _' to the end of each line but it still will not compile.
Any suggestions where I am going wrong? Many thanks
You have to put the SQL into a string...
Dim sql As String
sql = "SELECT blah FROM blah;"
Note that this means you have to insert all of the values and double up quotes:
sql = "SELECT blah "
sql = sql & " FROM blah "
sql = sql & " WHERE blah = ""some value"" "
sql = sql & " AND blah = """ & someVariable & """;"
After that, you have to do something with it. For SELECTs, open a recordset:
Dim rs AS DAO.Recordset
Set rs = CurrentDb.OpenRecordset(sql)
Or, for action queries, execute them:
CurrentDb.Execute sql, dbFailOnError
Without knowing how you plan to use it, we can't give much more info than that.
This conversion tool would be quite helpful for automating the process: http://allenbrowne.com/ser-71.html
I suggest to use single quotes inside your SQL string to not mess up the double quotes forming the string.
In my opinion it's a lot better readable than doubled double quotes.
Simplified:
Dim S As String
S = "SELECT foo FROM bar " & _
"WHERE foo = 'Global Challenges Research Fund' " & _
"HAVING (Summary Like '*" & strsearch & "*')"
Note the spaces at the end of each line.
Obligatory reading: How to debug dynamic SQL in VBA
Edit
To simplify handling user entry, I use
' Make a string safe to use in Sql: a'string --> 'a''string'
Public Function Sqlify(ByVal S As String) As String
S = Replace(S, "'", "''")
S = "'" & S & "'"
Sqlify = S
End Function
then it's
"HAVING (Summary Like " & Sqlify("*" & strsearch & "*") & ")"

SQL Variable in Where Clause

Dim varCity As String
varCity = Me.txtDestinationCity
Me.txtDestinationState.RowSource = "SELECT tPreTravelDestinationState FROM [TDestinationType] WHERE" & Me.txtDestinationCity & "= [TDestinationType].[tPreTravelDestinationCity]"
I am trying to select the states for the selected city. There is a drop down box with a list of cities. That box is titled txtDestinationCity.
It says I have an error in my FROM clause.
Thank you
You miss a space and some quotes. How about:
Me.txtDestinationState.RowSource = "SELECT tPreTravelDestinationState FROM [TDestinationType] WHERE '" & Me.txtDestinationCity & "' = [TDestinationType].[tPreTravelDestinationCity]"
Copy that next to your original to see the difference.
And for reasons SQL, PLEASE reverse the comparison. Always mention the column left and the value right:
Me.txtDestinationState.RowSource = "SELECT tPreTravelDestinationState FROM [TDestinationType] WHERE [TDestinationType].[tPreTravelDestinationCity] = '" & Me.txtDestinationCity & "'"
Since the quotes are annoying and easy to miss, i suggest defining a function like this:
Public Function q(ByVal s As String) As String
q = "'" & s & "'"
End Function
and then write the SQL string like that:
Me.txtDestinationState.RowSource = "SELECT tPreTravelDestinationState FROM [TDestinationType] WHERE [TDestinationType].[tPreTravelDestinationCity] = " & q(Me.txtDestinationCity)
This makes sure you ALWAYS get both quotes at the right places and not get confused by double-single-double quote sequences.
If you care about SQL-injection (yes, look that up), please use the minimum
Public Function escapeSQL(sql As String) As String
escapeSQL = Replace(sql, "'", "''")
End Function
and use it in all places where you concatenate user-input to SQL-clauses, like this:
Me.txtDestinationState.RowSource = "SELECT tPreTravelDestinationState FROM [TDestinationType] WHERE [TDestinationType].[tPreTravelDestinationCity] = " & q(escapeSQL(Me.txtDestinationCity))
Lastly, breakt it for readability. I doubt your editor shows 200 characters wide:
Me.txtDestinationState.RowSource = _
"SELECT tPreTravelDestinationState " & _
"FROM [TDestinationType] " & _
"WHERE [TDestinationType].[tPreTravelDestinationCity] = " & q(escapeSQL(Me.txtDestinationCity))
Note the trailing spaces in each line! Without them, the concatenation will not work.
It can be easier to troubleshoot your query construction if you set it to a variable (e.g., strSQL) first. Then you can put a breakpoint and see it right before it executes.
You need a space after WHERE. Change WHERE" to WHERE<space>"
Me.txtDestinationState.RowSource = "SELECT tPreTravelDestinationState FROM [TDestinationType] WHERE " & Me.txtDestinationCity & "= [TDestinationType].[tPreTravelDestinationCity]"

Incorrect syntax near 's'. Unclosed quotation mark after the character string

I'm using a query to pull data from an SQL database, at times the last dropdown im using to get the record i'm looking for has a single quote, when it does I get the following error: Incorrect syntax near 's'. Unclosed quotation mark after the character string
This is the code I have:
Using objcommand As New SqlCommand("", G3SqlConnection)
Dim DS01 As String = DDLDS01.SelectedItem.Text
Dim State As String = DDLState.SelectedItem.Text
Dim Council As String = DDLCouncil.SelectedItem.Text
Dim Local As String = DDLLocal.SelectedItem.Text
Dim objParam As SqlParameter
Dim objDataReader As SqlDataReader
Dim strSelect As String = "SELECT * " & _
"FROM ConstitutionsDAT " & _
"WHERE DS01 = '" & DS01 & "' AND STATE = '" & State & "' AND COUNCIL = '" & Council & "' AND LOCAL = '" & Local & "' AND JURISDICTION = '" & DDLJurisdiction.SelectedItem.Text & "' "
strSelect.ToString.Replace("'", "''")
objcommand.CommandType = CommandType.Text
objcommand.CommandText = strSelect
Try
objDataReader = objcommand.ExecuteReader
DDLJurisdiction.Items.Add("")
While objDataReader.Read()
If Not IsDBNull(objDataReader("SUBUNIT")) Then
txtSubUnit.Text = (objDataReader("SUBUNIT"))
End If
If Not IsDBNull(objDataReader("DS02")) Then
lblDS02.Text = (objDataReader("DS02"))
End If
If Not IsDBNull(objDataReader("LEGISLATIVE_DISTRICT")) Then
txtALD.Text = (objDataReader("LEGISLATIVE_DISTRICT"))
End If
If Not IsDBNull(objDataReader("REGION")) Then
txtRegion.Text = (objDataReader("REGION"))
End If
If DDLState.SelectedItem.Text <> "OTHER" Then
If Not IsDBNull(objDataReader("UNIT_CODE")) Then
txtUnitCode.Text = (objDataReader("UNIT_CODE"))
End If
End If
End While
objDataReader.Close()
Catch objError As Exception
OutError.Text = "Error: " & objError.Message & objError.Source
Exit Sub
End Try
End Using
Not all records contain a single quote, only some, so i'd need something that would work if a single quote is present or not.
Thanks.
Your problem is this line here:
strSelect.ToString.Replace("'", "''")
This is changing your WHERE clause from something like
WHERE DS01 = 'asdf' AND ...
To:
WHERE DS01 = ''asdf'' AND ...
You need to do the replace on the individual values in the where clause, not on the whole select statement.
What you should really be doing is using a parameterized query instead.
Update: added same link as aquinas because it's a good link
Use parameterized queries, and only EVER use parameterized queries. See: How do I create a parameterized SQL query? Why Should I?

VB6 and SQL mistake

Here is a line of code in SQL I am attempting to use in VB6.
Dim Sqlstring As String
Sqlstring = "Update TroubleTickets set ResolvedDate = ' " + DateValue(Now) + "' where Title ='" + Trim(TicketComboBox.Text) + "'"
I am getting an error that says types do not match when i run the debugger.
any suggestions?
Dim Sqlstring As String
Sqlstring = "Update TroubleTickets set ResolvedDate = ' " & DateValue(Now) & "' where Title ='" & Trim(TicketComboBox.Text) & "'"
The concat-operator in VB is the ampersand &.
You get a type mismatch error because VB expects a number if you use +.
You should also consider using prepared statements to insert parameters into SQL queries.