I have not done any VB6 work for a long time. Recently, I found that I need to a little bit of VB6 ADO code to an old application. So I have to re-research something that I was doing everyday years ago. I will record the results here so I don't have to do the same research again.
The first is regarding parameterized query (or someone call it prepared statement). Basically, ADO will use sp_executesql to send the command with the parameters. The execution plan is cached for the connection. If we send another command with same set of parameters (each parameter could have a different value), SQL server will reuse the execution plan.
To create a command that will send prepared statements, we need to use ? in place each parameter that we want to parameterize. For example:
cmd.CommandText = "select * from application where FIRST_NAME = ? and LAST_NAME = ? and BIRTH_DATE = ?"
Then we need to create the parameters, like:
cmd.Parameters.Append cmd.CreateParameter("FIRST_NAME", adVarChar, adParamInput, 20)
cmd.Parameters.Append cmd.CreateParameter("LAST_NAME", adVarChar, adParamInput, 20)
cmd.Parameters.Append cmd.CreateParameter("BIRTH_DATE", adDBTimeStamp)
When we need to execute the command, we can pass in the parameters like this:
cmd.Parameters("FIRST_NAME").value = Left$(strFirstName, 20)
cmd.Parameters("LAST_NAME").value = Left$(strLastName, 20)
cmd.Parameters("BIRTH_DATE").value = ConvertDate(vDateBirth)
Note that if the value we pass in is too long, we will get an error. Also, we need to pass in value of every parameter, even if it is null. Otherwise, we will get:
-2147467259-[Microsoft][ODBC SQL Server Driver]Invalid use of default parameter
Lastly, if we have a text column, here is the way to create the parameter:
cmd.Parameters.Append cmd.CreateParameter("RESPONSE_STRING", adLongVarChar, adParamInput, -1)
Then here is the way to pass in the value in chunks:
Private Sub WriteTextToTextParameter(param As ADODB.Parameter, value As String)
Const BLOCK_SIZE = 2048
Dim l As Integer
Dim pos As Integer
l = Len(value)
If l = 0 Then
param.value = Null
Else
Do While pos < l
If (pos + BLOCK_SIZE) < l Then
param.AppendChunk (Mid$(value, pos + 1, BLOCK_SIZE))
Else
param.AppendChunk (Mid$(value, pos + 1))
End If
pos = pos + BLOCK_SIZE
Loop
End If
End Sub