Date/Time Conversion Failure in VBA using SQL Database Query - mysql

First thing's first. Here's my code.
Dim conn As ADODB.Connection
Dim rec1 As ADODB.Recordset
Dim connStr As String
Dim thisSql As String
Dim testStr As String
Sub Button3_Click()
Worksheets("Sheet5").Range("N1") = Worksheets("Sheet5").Range("N1") + 1
Set conn = New ADODB.Connection
connStr = "DSN=myDatabase;UID=myUsername;PWD=myPassword;APP=Microsoft Office 2013;WSID=myPCname;DATABASE=myDatabase"
conn.Open connStr
thisSql = "SELECT myDatabase.OrderNumber, myDatabase.CustomerName, myDatabase.ShipProd, myDatabase.Sum of Sales, myDatabase.InvoiceDate FROM myDatabaseAddress "
thisSql = thisSql & "WHERE (myDatabase.ShipProd Like '" & Worksheets("Sheet5").Range("C2") & "') "
thisSql = thisSql & "GROUP BY myDatabase.CustomerName, myDatabase.OrderNumber, myDatabase.InvoiceDate, myDatabase.ShipProd, myDatabase.OEELPrimarySlsCrdtWhse "
thisSql = thisSql & "HAVING (myDatabase.OEELPrimarySlsCrdtWhse Like 'MI%') "
thisSql = thisSql & "AND (myDatabase.InvoiceDate Between {ts '" & Worksheets("Sheet5").Range("E2") & "'} And {ts '" & Worksheets("Sheet5").Range("F2") & "'}) "
thisSql = thisSql & "ORDER BY myDatabase.CustomerName ASC"
Set rec1 = New ADODB.Recordset
rec1.Open thisSql, conn
Worksheets("Sheet5").Range("A3:F10000").Clear
With Worksheets("Sheet5").QueryTables.Add(Connection:=rec1, Destination:=Worksheets("Sheet5").Range("A3"))
.Name = "data"
.FieldNames = True
.Refresh BackgroundQuery:=False
End With
End Sub
I am trying to send a query with parameters and bring back some results from my SQL database. One of the parameters that I want to pass is a date range that InvoiceDate must fall between. These dates are located in cells E2 and F2. When I run the code, I receive an error that says
Run-time error '-2147217913 (80040e07)':
[Microsoft][ODBC SQL Server Driver][SQL Server]Conversion failed when converting date and/or time from character string.
When I push "Debug" on the message box, it highlights the line with the code
rec1.Open thisSql, conn
I have tried formatting the cells in the spreadsheet many different ways including yyyymmdd and m/d/yyyy h:mm and mm/dd/yyyy hh:mm:ss.
Another problem that I'm running into is that one of the field names is "Sum of Sales". This section generates an error saying that "of" is a reserved keyword.
If there are any suggestions that anyone has, that would be greatly appreciated.
UPDATE
I managed to fix the date/time error by changing
thisSql = thisSql & "AND (myDatabase.InvoiceDate Between {ts '" & Worksheets("Sheet5").Range("E2") & "'} And {ts '" & Worksheets("Sheet5").Range("F2") & "'}) "
to
thisSql = thisSql & "AND (myDatabase.InvoiceDate Between '" & Worksheets("Sheet5").Range("E2") & "' And '" & Worksheets("Sheet5").Range("F2") & "') "
Although, I am still working on fixing the field name problem. I have tried putting 'myDatabase.Sum of Sales' in single quotes like it is here, but that just returns "myDatabase.Sum of Sales" in all of the cells in the corresponding column.

Related

Select from where contains

I have a database where i can add a full name of a person, and i am trying to implement a search function using a textBox and a button but i only want to search for the first or last name not necessarily entering the full name.
I tried using SELECT FROM WHERE CONTAINS like this:
OleDbCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM Table WHERE CONTAINS (column, '"+textBox.Text+"')";
But i keep getting this error:
Syntax error (missing operator) in query expression 'CONTAINS (column,'the text i tried to search')'.
I also tried changing the + to % or * or & but still it didn’t work.
Contains is not valid Access SQL. Use Like:
cmd.CommandText = "SELECT * FROM Table WHERE [YourNameField] Like '*" + textBox.Text + "*')";
Here is an example of a search such as you want:
Private Sub cmdFind_DisplayName_Click()
Dim dbs As Database, rstPatient As Recordset
Dim txtDisplayName, strQuote As String
strQuote = Chr$(34)
On Error GoTo ErrorHandler
Me.OrderBy = "DISPLAYNAME"
Me.OrderByOn = True
Set dbs = CurrentDb
Set rstPatient = Me.RecordsetClone
txtDisplayName = Trim(InputBox("Please Enter Patient Name ", "Patient Find By Name"))
txtDisplayName = UCase(txtDisplayName) & "*"
If IsNull(txtDisplayName) Then
MsgBox ("No Patient Name Entered - Please Enter a Valid Patient Name")
Else
rstPatient.FindFirst "[DISPLAYNAME] Like " & strQuote & txtDisplayName & strQuote
If Not (rstPatient.NoMatch) Then
Me.Bookmark = rstPatient.Bookmark
Me.Refresh
Else
MsgBox ("Patient Not Found - Please Enter a New Patient Name")
End If
End If
GoTo Exit_cmdFind_Click
ErrorHandler:
MsgBox LTrim(RTrim(Me.NAME)) + "." + "Patient Find By Display Name - " + "Error: " + AccessError(Err.Number)
Exit_cmdFind_Click:
rstPatient.Close
Set dbs = Nothing
Set rstPatient = Nothing
End Sub
Create 1 textbox (txtMain) and search command button(btnSearch) to execute SQL. Then add a listbox (listResult) to display results.
Private Sub btnSearch_Click()
Dim mainSQL As String
mainSQL = " SELECT YOUR_FIELD_NAME " & _
" FROM MasterReg " & _
" WHERE Left(,InStr(YOUR_FULL_NAME_FIELD,' ')-1) LIKE '" & me.txtMain & "*'" & _ ' Firstname Search
" OR RIGHT( YOUR_FULL_NAME_FIELD,Len( YOUR_FULL_NAME_FIELD )-InStr( YOUR_FULL_NAME_FIELD,' ')) LIKE '" & me.txtMain & "*'" 'Surname Search
Me.listResult.SetFocus
Me.listResult.RowSource = mainSQL
Me.listResult.Requery
End Sub

Creating a form to search for records based on multiple criteria

I am trying to create a form that allows you to return results based on multiple criteria.
I have FirstName field, LastName field, and State Field.
I also have an text boxes named searchFirst, searchLast, searchState where users can input criteria.
The search button will execute the following code once clicked.
Private Sub mySearchQuery_Click()
Dim filter As String
Dim rtFirstName As String
Dim rtLastName As String
Dim rtState As String
rtFirstName = Me.searchFirst.Value
rtLastName = Me.searchLast.Value
rtState = Me.searchState.Value
If Not IsNull(rtFirstName) Then
If Not IsNull(filter) Then filter = filter & " AND "
filter = filter & "(FirstName like""*" & rtFirstName & "*"")"
End If
If Not IsNull(rtLastName) Then
If Not IsNull(filter) Then filter = filter & " AND "
filter = filter & "(LastName like""*" & rtLastName & "*"")"
End If
If Not IsNull(rtState) Then
If Not IsNull(filter) Then filter = filter & " AND "
filter = filter & "(State LIKE""*" & rtState & "*"")"
End If
' Now re-construct the SQL query '
Dim sql As String
sql = "SELECT * FROM MainData"
If Not IsNull(filter) Then
sql = sql & " WHERE " & filter
End If
Me.RecordSource = sql
'SubForm.Form.RecordSource = sql
End Sub
I am getting the following error below.
Run-time error '3075': Syntax error (missing operator) in query
expression 'AND (FirstName like"*tracy*") AND (lastName like"*Smith*")
AND (State LIKE"*ga*")'.
I am not sure why AND was included at the beginning of the search query?
I am not sure why AND was included at the beginning of the search
query?
Since you have Dim filter As String, filter can never contain Null. That means these If conditions ... If Not IsNull(filter) ... will always be True.
Similarly, Not IsNull(rtFirstName), Not IsNull(rtLastName), and Not IsNull(rtState) will always be True.
The net result is the code adds another condition piece to your filter string regardless of whether or not the corresponding search text box contains anything, and each of those pieces is prefixed with " AND ".
With those points in mind, you could refactor your code to add a filter segment only when you have something in the corresponding search text box and decide when to include " AND ". However I find it simpler to include " AND " for each of them and then strip away the very first " AND " from filter before adding it to the WHERE clause.
Private Sub mySearchQuery_Click()
Dim strSelect As String
Dim strWhere As String
If Len(Trim(Me!searchFirst.Value) & vbNullString) > 0 Then
strWhere = strWhere & " AND FirstName Like ""*" & Me!searchFirst.Value & "*"""
End If
If Len(Trim(Me!searchLast.Value) & vbNullString) > 0 Then
strWhere = strWhere & " AND LastName Like ""*" & Me!searchLast.Value & "*"""
End If
If Len(Trim(Me!searchState.Value) & vbNullString) > 0 Then
strWhere = strWhere & " AND State Like ""*" & Me!searchState.Value & "*"""
End If
' Now re-construct the SQL query
strSelect = "SELECT * FROM MainData"
' only add WHERE clause if we have something in strWhere
If Len(strWhere) > 0 Then
' use Mid() to ignore leading " AND "
strSelect = strSelect & " WHERE " & Mid(strWhere, 6)
End If
Debug.Print strSelect ' <- inspect this in Immediate window; Ctrl+g will take you there
' enable one of these RecordSource lines after confirming Debug.Print shows you what you need
'Me.RecordSource = sql
'SubForm.Form.RecordSource = sql
End Sub

Current system datetime syntax in VB6.0 which is equivalent to sql datetime

brdSrNo = txt_Board_SrNo.Text
usrname = txt_User_Name.Text
ndate = Format$(Now, "yyyy-mm-dd hh:mm:ss")
voltMeas1 = txt_VoltMes.Text
rs.Open "insert into duct_test values(" & brdSrNo & ",'" & ndate & "'," & usrname & ", " & voltMeas1 & ")", con, adOpenDynamic, adLockBatchOptimistic
'here I get the error'
I tried the above code but the error appears as:Incorrect syntax near','. Is there anyway to get the datetime like this:2015-10-30 17:09:22.000, as we get in sql
thanks #nabuchodonossor & #Fred, I got the Datetime pblm fixed. Now I got another error.. where, if voltMeas1=12.5 r something that takes an voltage measure... the error shows : "Arithmetic overflow error converting numeric to datatype numeric" ,In the sql table VoltageMeasure data type is Numeric(2,2).. can u suggest anthying?
you can also use the server time:
instead of:
rs.Open "insert into duct_test values(" & brdSrNo & ",'" & ndate & "'," & usrname & ",
you can write:
rs.Open "insert into duct_test values(" & brdSrNo & ", GETDATE(), " & usrname & ",
and implement the changes of mentioned by Fred
I can see a couple of things wrong here
You are inserting a record so you do not need a recordset as you are not returning anything. Use cmd .Execute instead of rs.Open.
usrname is a string so needs to be wrapped in single quotes '
Your final code should like more like:
Private Sub cmd_update_Click()
Dim strSQL As String
Dim con As ADODB.Connection
Set con = New ADODB.Connection
con.ConnectionString = "Provider=SQLOLEDB;Data Source=SUVI.suvi.local;InitialCatalog=SUVI;Database=BLS;uid=sa;pwd=123458;"
con.Open
strSQL = "insert into duct_test values(" & brdSrNo & ", GetDate(),'" & usrname & "', " & voltMeas1 & ")"
con.Execute strSQL, , adCmdText
con.Close
Set con = Nothing
End Sub
As a side note it is advisable to replace single quotes in any data input by a user with double single quotes. For example:
usrname = Replace$(usrname, "'", "''")
This will help against SQL injection attacks. Im not saying it will total prevent this but it will help.
If the date you are inserting is always the current date and time you can, as
nabuchodonossor point out, use GetDate().

Data mismatch error 3464

I'm very new to VBA so I'm not even sure if I'm heading in the right direction.
I'm using Access 2010 and I've created a form where you search for an ID and then you click to add a new record for multiple timepoints (e.g follow-up form for timepoint 1, 2, 3, 4).
I have a StudyPeriod field (long integer) where you select from a list (via query number + text). I want an error box to come if that time period has already been entered.
I've been trying to use this code but it keeps coming up with the 3464 runtime error and the de-bug highlights the If Me. line.
What am I doing wrong?
Private Sub StudyPeriod_AfterUpdate()
Dim StudyPeriod As String
Dim StLinkCriteria As String
StudyPeriod = Me.StudyPeriod.Value
StLinkCriteria = "[StudyPeriod] = " & "'" & StudyPeriod & "'"
' If line below returns error
If Me.StudyPeriod = DLookup("[StudyPeriod]", "3_Questionnaire", StLinkCriteria) Then
MsgBox "This questionnaire has already been entered for this participant." _
& vbCr & vbCr & "Please check RegID or Summary table.", vbInformation, _
"Duplicate information"
Me.Undo
End If
End Sub
Your StudyPeriod field in your 3_Questionnaire table is a numeric datatype (Long Integer). So do not include quotes before and after the value of your StudyPeriod variable when you build the StLinkCriteria string:
'StLinkCriteria = "[StudyPeriod] = " & "'" & StudyPeriod & "'"
StLinkCriteria = "[StudyPeriod] = " & StudyPeriod
If Me.StudyPeriod = DLookup("[StudyPeriod]", "3_Questionnaire", StLinkCriteria) Then

AM I using DO WHILE NOT and EOF in VBscript Properly

Finally the administrator configured the IIS for me the error message is listed below.
Set SQLStream = CreateObject("ADODB.Stream")
Set SQLConnection = CreateObject("ADODB.Connection")
Set SQLCommand = CreateObject("ADODB.Command")
Set SQLRecordSet = CreateObject("ADODB.RecordSet")
SQLConnection.Open "Provider=sqloledb;SERVER=SQLPROD;DATABASE=MyDataBase;UID=MyUsername;PWDMyPassword;"
'Response.Write("Connection Status: " & SQLConnection.State) & vbnewline
'Response.Write("Connection Provider: " & SQLConnection.Provider) & vbnewline
'Response.Write("Version: " & SQLConnection.Version) & vbnewline
SQLCommand.ActiveConnection = SQLConnection
SQLCommand.CommandText = "SELECT Seminars.Year, Seminars.SeminarID, Seminars.Theme, Seminar_Week.First, Seminar_Week.Last, Seminar_Week.WeekID, Seminar_Week.Date, Seminar_Week.Affiliation FROM Seminars CROSS JOIN Seminar_Week"
'Response.Write("SQL Command Passed in: " & SQLCommand.CommandText)
Set adoRec = SQLCommand.Execute()
file1 = "./seminars/" & seminar_type & "/" & seminar_year & "/" & adoRec("Date") & "-" & adoRec("Year") & "_" & adoRec("Last") & ".pdf"
file2 = "./seminars/" & seminar_type & "/" & seminar_year & "/" & adoRec("Date") & "-" & seminar_year & "_" & adoRec("Last") & "(handouts).pdf"
file3 = "./seminars/" & seminar_type & "/" & seminar_year & "/" & adoRec("Date") & "-" & seminar_year & "_" & adoRec("Last") & "_Flyer.pdf"
Set fso = CreateObject("scripting.filesystemobject")
Response.Write("<p style=" & "margin-left:10px;" & "><img src=" & "./img/right_arrowblue.png" & " alt=" & "Expand/Collapse" & " id=" & "arrow_" & adoRec("Week") & " /><strong>[" & adoRec("Date") & "]</strong> " & ""&aroRec("First") & adoRec("Last") & ", " & adoRec("Affiliation") & "</p>")
The very last line of code causes this error
ADODB.Recordset error '800a0cc1'
Item cannot be found in the collection corresponding to the requested name or ordinal.
FilePath, line 244
Line 244 is the very last line of code that should write Some information about each seminar on the webpage.
I'm pretty sure at this point I am pointing to an incorrect file path because I have an extra space somewhere in all the different string.
My question now is Would the ones in the very beginning, meaning the ones used in
"<p style=" & "margin-left:10px;" & "><img src=" & "./img/right_arrowblue.png"
be causing the trouble.
I'm also unfamiliar with using the "Expand/collapse" so if someone could tell me a little more about that. I am trying to fix someone elses code so I am a little behind the 8 ball.
One small step to a solution:
Your SQL
"SELECT * FROM Seminars WHERE [SeminarID] = 5 ORDER BY DESC"
is definitely wrong: ORDER BY needs (at least) a column name: ORDER BY [SeminarID] DESC.
If that does not solve all your problems, we'll have to think about a step by step approach.
If you get errors, tell us about them (number, description, line). That's what I meant, when I ask you to publish them. If you can't better info than "There was an error when processing the URL" from IIS, then you have to write some command line script to get the database related code absolutely right.
Start with experiments.vbs:
Dim sCS : sCS = !your connection string!
Dim oCN : Set oCN = CreateObject("ADODB.Connection")
oCN.Open sCS
WScript.Echo "CN open:", oCN.State
Dim sSQL : sSQL = !your SQL statement!
Dim oRS : Set oRS = oCN.Execute(sSQL)
WScript.Echo "RS EOF:", CStr(oRS.EOF)
WScript.Echo "Frs Col:", oRS.Fields(0).Name, oRS.Fields(0).Type
Dim i : i = 0
Do Until oRS.EOF
WScript.Echo i, oRS.Fields(0).Value
i = i + 1
oRS.MoveNext
Loop
oCN.Close
and run it in a command window (DOS box): cscript experiments.vbs. This should get you either some lines like:
CN open: 1
RS EOF: False
Frs Col: Id 3
0 ...
1 ...
2 ...
or a focused/publishable error message like:
... .vbs(2465, 14) Microsoft OLE DB Provider for SQL Server: Falsche Syntax in der Nä
he des 'DESC'-Schlüsselworts.
(bad syntax near DESC), which got when I tried the statement
"SELECT * FROM Alpha ORDER BY DESC"
RS.MoveNext
Put the above code on the line before the Loop keyword to avoid an infinite loop.
Are you missing the loop keyword at the end of your loop block?
Check the syntax here: http://msdn.microsoft.com/en-us/library/eked04a7.aspx