Ms Access VBa where condition with (And) Error - database

i have a problem or lets say an error i get
i'm having that "Run Time-error '13' type mismatch" error when running this code
DoCmd.OpenReport "hamw_m3amala_naw_w_mawad", acViewReport, , "Jori_Mawad = '" & Combo14 & "' " And "ID =" & Combo4
note that Jori_Mawad is String and ID is Number
and that this two condition without the (And) do not have any problem and works fine :
DoCmd.OpenReport "hamw_m3amala_naw_w_mawad", acViewReport, , "Jori_Mawad = '" & Combo14 & "'"
DoCmd.OpenReport "hamw_m3amala_naw_w_mawad", acViewReport, , "ID = " & Combo4

Your
And
should be within the string that you are using as a where clause, but you are instead And-ing the first part of your clause with the second.
try
"Jori_Mawad = '" & Combo14 & "' And ID =" & Combo4

Related

Insert NULL value into SQL Server from Classic ASP

I am trying to do a simple insert or update into SQL Server as NULL, not blank. I have seen many references online to just set Field = NULL without quotes but it is still coming up as empty, not NULL. Incredibly frustrating.
This is in classic asp.
If Request.Form("Field") = "" or IsNull(Request.Form("Field")) then
Field = NULL
Else
Field = Request.Form("Field")
End If
sSql="UPDATE [table] SET timestamp = {fn NOW()}," &_
"Field = '" & Field & "'," &_
"WHERE [System] = '" & System & "' and Active = '1'"
If I do this, it proves that it is checking because it puts in a 1.
If Request.Form("Field") = "" or IsNull(Request.Form("Field")) then
Field = 1
Else
Field = Request.Form("Field")
End If
sSql="UPDATE [table] SET timestamp = {fn NOW()}," &_
"Field = '" & Field & "'," &_
"WHERE [System] = '" & System & "' and Active = '1'"
I tried this but get an error 500:
sSql="UPDATE [Table] SET timestamp = {fn NOW()}, Field = "
If IsNull(Field) Then
sSQL = sSQL & "NULL"
Else
sSQL = sSQL & "'" & Field & "'" &_
End If
"NTLogon = '" & UCase(NTLogon) & "'" &_
"WHERE [System] = '" & System & "' and Active = '1'"
When I try this in place of my original code:
Field Assignment:
Field = "NULL" and Field = "'" & Request.Form("Field") & "'"
sSQL:
"Field = " & Field & "," &_
I get "An error occurred on the server when processing the URL."
So yeah, insert rant here about using parameterized queries, blah blah blah... now that's out of everyone's system, could we maybe look at the actual question?
The problem is this:
"Field = '" & Field & "'"
Those ampersands are converting your lovingly-populated vbScript NULL value right back into a string. If you don't want that to happen, you need to explicitly handle the IsNull case.
sSQL = "UPDATE [table] SET timestamp = {fn NOW()}, Field = "
If IsNull(Field) Then
sSQL = sSQL & "NULL"
Else
sSQL = sSQL & "'" & Field & "'"
End If
sSQL = sSQL & " WHERE [System] = '" & System & "' AND Active = '1'"
Note that even if you do this via a parameterized query, you'll need to make sure you're not appending your vbScript NULL value onto a string, because "" & NULL = "".
#pinchetpooche Hello there. I had the same issue and tried the given answer, and also received a 500 error page. I found that #Martha forgot to include the necessary SQL field that is being updated (i.e., "Field"). So I put together some test code, using her solution (i.e., using string concatenation and conditional logic), and executed against an actual database, and this solution works perfectly:
sSQLNullTest = "UPDATE CustomersToCCData SET "
sSQLNullTest = sSQLNullTest & "CustomerID = " & iCustomerID & ", "
If IsNull(x_license_number_state) Or x_license_number_state = "" Then
sSQLNullTest = sSQLNullTest & "CCLicenseState = NULL"
Else
sSQLNullTest = sSQLNullTest & "CCLicenseState = '" & x_license_number_state & "' "
End If
sSQLNullTest = sSQLNullTest & " WHERE CCID = '" & iCCInfoCCID & "'

Access VBA ODBC connection failed

I have an Access Frontend with a SQL Server backend.
On one of the forms, there is a bit of VBA to keep an "Audit Log" of the changes.
In one procedure there are these 2 bits of code, the first works, but the second gives an error
Working:
sSQL = "DELETE FROM [dbo_EventReport_Audit_Temp_Before];"
CurrentProject.Connection.Execute sSQL
Not working a few lines down:
sSQL = "INSERT INTO [dbo_EventReport_Audit_Temp_Before] (<TABLE COLUMNS>) SELECT <TABLE COLUMNS> FROM [dbo_EventReport] WHERE ((Event_ID)= <EVENT_ID>");"
CurrentProject.Connection.Execute sSQL
So the first statement deletes any records in the table. This works fine, as I've inserted dummy data and stepped through the code and seen it be deleted.
But the second statement causes an error:
Error -2147467259: ODBC--connection to 'EventsDB' failed.
Anyone any idea why the first statement works ok, but the second fails?
Extracting the value of sSQL for the second statement and manually running it through an SQL Query in Access inserts the data into the table.
EDIT:
I didn't want to post the full statement as it's a bit of a monster. But here is is:
sSQL = "INSERT INTO " & sAudTmpTable & " ( [audType], [audDate], [audUser], [Event_Number], [Event_ID], " & _
"[Received_Date], [Response_Date], [Site], [Server], [Workstation], [Software_Version], [Data_Version], " & _
"[Description], [Test_Description], [Company], [Observed_By], [Observed_Date], [Tested_By], [AssignedTo], " & _
"[Tested_Date], [Test_Result], [Ind_Tested_By], [Ind_Tested_On], [Ind_Test_Result], [Reviewed_By], " & _
"[Actioned_Date], [Review_Date], [Review_Result], [Completed_By], [Completed_Date], [Closed_By], " & _
"[Closed_Date], [Exclude], [Category], [State], [Event_Responsibility], [Probability], [WIP_Number], " & _
"[OriginalWIP], [Severity], [Blocked], [Block_Description], [Tags], [Work], [TaskID], [EventType], " & _
"[DefectType], [known_issue_impact], [known_issue_description], [Operator_Notes], [BugWIP], " & _
"[SupplierName], [SupplierCompany], [Simulator], [ATSTest], [FixPriority] ) " & _
"SELECT '" & EditOrInsert & "' AS Expr1, '" & DateTime & "', '" & User & "', [Event_Number], [Event_ID], " & _
"[Received_Date], [Response_Date], [Site], [Server], [Workstation], [Software_Version], [Data_Version], " & _
"[Description], [Test_Description], [Company], [Observed_By], [Observed_Date], [Tested_By], [AssignedTo], " & _
"[Tested_Date], [Test_Result], [Ind_Tested_By], [Ind_Tested_On], [Ind_Test_Result], [Reviewed_By], " & _
"[Actioned_Date], [Review_Date], [Review_Result], [Completed_By], [Completed_Date], [Closed_By], " & _
"[Closed_Date], [Exclude], [Category], [State], [Event_Responsibility], [Probability], [WIP_Number], " & _
"[OriginalWIP], [Severity], [Blocked], [Block_Description], [Tags], [Work], [TaskID], [EventType], " & _
"[DefectType], [known_issue_impact], [known_issue_description], [Operator_Notes], [BugWIP], " & _
"[SupplierName], [SupplierCompany], [Simulator], [ATSTest], [FixPriority] " & _
"FROM [" & sTable & "] WHERE ((" & sKeyField & ")=" & lngKeyValue & ");"
You reported this attempt fails ...
CurrentProject.Connection.Execute sSQL
... but this works using the same sSQL statement ...
CurrentDb.Execute sSQL, dbFailOnError + dbSeeChanges
CurrentProject.Connection.Execute is an ADO method. CurrentDb.Execute is a DAO method. The two methods are similar, but not the same.
One important difference is the ADO version is more likely to fail when the SQL statement includes reserved words as object (table, field, etc.) names; DAO is more forgiving about problem names.
But there are other differences, and it is not possible to determine which of them was the key factor for an INSERT statement we haven't seen. ;-)

Inserting a string formed of variables into an MSSQL database using VBScript

I have a database with a table called LaptopTrolleyWU that has the following structure:
ComputerName varchar(50)
TimeStamp datetime
Log varchar(MAX)
I am trying to insert text into the Log field from a VBScript script, but cannot work out the syntax in order to do so.
This is what I have so far:
For I = 0 to updatesToInstall.Count - 1
WScript.Echo I + 1 & "> " & _
updatesToInstall.Item(i).Title & _
": " & installationResult.GetUpdateResult(i).ResultCode
objFile.WriteLine(I + 1 & "> " & updatesToInstall.Item(i).Title & ": " & installationResult.GetUpdateResult(i).ResultCode)
Connection.Execute "INSERT INTO LaptopTrolleyWU (Log) VALUES ('" & I + 1 & "'> '" & updatesToInstall.Item(i).Title & "': '" & installationResult.GetUpdateResult(i).ResultCode & "')"
Next
End If
I get an error that reads
'Microsoft OLE DB Provider for ODBC Drivers: [Microsoft][ODBC SQL
Server Driver][SQL Server][Incorrect syntax near ')'.
What am I doing wrong?
If it helps, this is how I originally connect to the DB, which I might have done incorrectly...
Set Connection = CreateObject("ADODB.Connection")
Set Recordset = CreateObject("ADODB.Recordset")
Dim ConnectionString
ConnectionString = "Driver={SQL Server};Server=server;Trusted_Connection=no;Database=LaptopTrolly;Uid=Laptop;Pwd=password"
Connection.Open ConnectionString
This is what I did in the end:
strLogText = I + 1 & "> " & updatesToInstall.Item(i).Title & ": " & installationResult.GetUpdateResult(i).ResultCode
strSQLCmd = "INSERT INTO dbo.LaptopTrolleyWU (ComputerName,TimeStamp,Log) VALUES ('" + strComputerName + "', '" + dtTimeStamp + "' , '" + strLogText + "')"
Connection.Execute strSQLCmd
Your task is to write the value of a string expression into a log file and a database field (I assume the .Echo is just for debugging). Then you should invest into a variable to hold the value of the expression and use that twice:
v = I + 1 & "> " & updatesToInstall.Item(i).Title & ": " & installationResult.GetUpdateResult(i).ResultCode
Writing to a file is easy, because you just need the plain data:
objFile.WriteLine v
(no spurious param list ()!). You need an INSERT statement to put v into the database; the value of v has to be single quoted:
>> v = "pipapo"
>> s = Replace("INSERT INTO LaptopTrolleyWU (Log) VALUES ('#v')", "#v", v)
>> WScript.Echo s
>>
INSERT INTO LaptopTrolleyWU (Log) VALUES ('pipapo')
>>
If you then do
WScript.Echo s
Connection.Execute s
you can be sure that the statement you execute is the code you have visually inspected.
Your expressions differ:
I + 1 & "> " & updatesToInstall.Item(i).Title & ": " & installationResult.GetUpdateResult(i).ResultCode
I + 1 & "'> '" & updatesToInstall.Item(i).Title & "': '" & installationResult.GetUpdateResult(i).ResultCode
The extra single quotes in the INSERT statement make the SQL parser assume you want to compare string literals.

MS-SQL Server search table using assembled criteria

I have a search page that returns results according to the criteria nominated and this works ok when each criteria is OR but when I use AND it returns bad or no results. For example the search criteria might be...
A. Author = ""
B. Subject = ""
C. Keyword = ""
D. Dated = ""
Code:
SELECT *
FROM Table
WHERE Author = '" & strAuthor & "'
AND Subject = '" & strSubject & "'
AND Keyword = '" & strKeyword & "'
AND Dated = '" & strDated & "' "
Here I have used only 4 parameters whereas in fact there are quite a few more. But the example should explain the problem... to make this work I would need to be more specific such as "if A and B" or "B, C and D" but using any parameters that are blank or NULL will not work.
Now I could write in the criteria using a conditional statement like...
SELECT *
FROM Table
WHERE
if strAuthor <> "" then
Author = '" & strAuthor & "'
end if
if strSubject <> "" then
AND Subject = '" & strSubject & "'
end if
and so on, except that writing SELECT strings like this does not work, just produces errors because the select string cannot contain additional code (that has been my finding).
If the options were only a few I could write separate select strings for each combination, but there are more than 10 different criteria which entail more than 3,628,800 combinations!
Is there a solution for this?
Here you are having 2 options:
a) Create a stored procedure and have some default value for all the columns, and in case if user doesn't pass any value, the query would run with the default value for that column.
b) Impose the rule on the front end to always select a value for all the columns.
No stored procedures are needed when using this code:
SQL = "SELECT * FROM Table WHERE ID <> ''"
if len(strAuthor) > 3 then
SQL = SQL & " AND Author = '" & strAuthor & "'"
end if
if len(strSubject) > 3 then
SQL = SQL & " AND Subject LIKE '%" + Replace(strSubject, "'", "''") + "%'"
end if
if len(strKeyword) > 3 then
SQL = SQL & " AND Description LIKE '%" + Replace(strKeyword, "'", "''") + "%'"
end if
if strCatID <> "" then
SQL = SQL & " AND Category = '" & strCatID & "'"
end if
SQL = SQL & " Order By Subject ASC "
The significance of the first line where it requests ID is to serve as a generic placeholder so that all following parameters can be prefixed with "AND".
If a variable is empty it is not included, so only those specified are used.

Visual Studio Database custom criteria search wont work

I have created a database in Visual Studio and I am coding with VB.net I have created textboxes and checkboxes to match the fields that each will search when the search button is pressed .
whenever i perform a search using the text boxes and checkbox i get an error.
Item Name , Room , Broken, In Use, floor, are the fields searched by the tehe text in NameSearch, RoomSearch, BrokenSearchare, InUseSearch ,FloorSearchrespectivly ....etc
this is thee code for the search button
Private Sub SearchButton_Click(sender As Object, e As EventArgs) Handles SearchButton.Click
RecordDataGridView.Refresh()
Me.RecordBindingSource.Filter = "[Item Name]= '" & NameSearch.Text & "' And [Room]= '" & RoomSearch.Text & "' And [Make]= '" & MakeSearch.Text & _
"' And [Broken]= '" & BrokenSearch.CheckState & "' And [Replaced]= '" & ReplacedSearch.CheckState & "'And [ID#]= '" & IdentificationNumberSearch.Text & _
"' And [Floor]= '" & FloorSearch.Text & "' And [In Use]= '" & InUseSearch.CheckState & "'"
Me.RecordTableAdapter.Fill(Me.MLGDatabaseDataSet.Record)
RecordDataGridView.Refresh()
End Sub
the error
for example I enter a text into item nameSearch and floorSearch and press search ,no result will be turned up as the other text boxes have no text in them.
Without addressing other issues, such as using a parameterized query to prevent SQL injections or using StringBuilder to more efficiently perform concatenation, I believe your issue may be a missing space in this snippet:
ReplacedSearch.CheckState & "'And [ID#]= '"
if you change this to
ReplacedSearch.CheckState & "' And [ID#]= '"
it may resolve the immediate error. However, you almost certainly have additional logic errors introduced by the OR statement in the middle (you probably want to surround the two clauses that are ORed with parentheses).
I spotted the same thing as #competent_tech. I would set it up this way to make it easier to debug.
Dim strFilter As String = _
"[Item Name]= '" & NameSearch.Text & _
"' And [Room]= '" & RoomSearch.Text & _
"' And [Make]= '" & MakeSearch.Text & _
"' And [Broken]= '" & BrokenSearch.CheckState & _
"' Or [Replaced]= '" & ReplacedSearch.CheckState & _
"' And [ID#]= '" & IdentificationNumberSearch.Text & _
"' And [Floor]= '" & FloorSearch.Text & _
"' And [In Use]= '" & InUseSearch.CheckState & "'"
Debug.Print(strFilter)
RecordBindingSource.Filter = strFilter
Edit: you want to filter only when there are conditions given
'filter string
Dim strFilter As String = ""
'for check boxes you probably want to filter only if checked
If BrokenSearch.CheckState = CheckState.Checked Then strFilter += "And [Broken]= " & BrokenSearch.CheckState & " "
If ReplacedSearch.CheckState = CheckState.Checked Then strFilter += "And [Replaced]= " & ReplacedSearch.CheckState & " "
If InUseSearch.CheckState = CheckState.Checked Then strFilter += "And [In Use]= " & InUseSearch.CheckState & " "
'for text boxes you want to filter only if has text
If IdentificationNumberSearch.Text.Length > 0 Then strFilter += "And [ID#]= '" & IdentificationNumberSearch.Text & "' "
If FloorSearch.Text.Length > 0 Then strFilter += "And [Floor]= " & FloorSearch.Text & " "
If RoomSearch.Text.Length > 0 Then strFilter += "And [Room]= " & RoomSearch.Text & " "
If MakeSearch.Text.Length > 0 Then strFilter += "And [Make]= '" & MakeSearch.Text & "' "
If NameSearch.Text.Length > 0 Then strFilter += "And [Item Name]= '" & NameSearch.Text & "' "
'check to make sure there is at least one condition
If strFilter.Length > 0 Then
'remove the first "And"
strFilter = strFilter.Remove(0, 4)
'output
Debug.Print(strFilter)
'set to filter
RecordBindingSource.Filter = strFilter
End If
Edit: Your error "Cannot perform '=' operation on System.Boolean and System.String" I think the problem is that the filter value has to match the field type.
For strings do this: [Make] = 'stringValue' using single quotes;
For integers do this: [Floor] = 24 without single quotes;
For bit do this: [Broken] = 1 without single quotes;
It looks like Broken, Replaced and In Use are Bit type in the database. And I'm guessing that Floor and Room are Integer.

Resources