SQL INSERT INTO VALUE statement using a SELECT statement with a variable - sql

I have 2 tables:
Tbl_Task - Has all the tasks for a process (TaskNum is unique. TaskName is what i'm writing to Tbl_Proc)
Tbl_Proc - Will hold the status of each task for a customer
When a new customer is created, I'm using the forms on close event to write each task from Tbl_Task into Tbl_Proc. I'm using the customer name from the form to complete the record in the Tbl_Proc.
My thought is to use an integer to increment the TaskNum and assign that task numbers TaskName to the Tbl_Proc[ProcTaskName]. Then loop through all task numbers. As you can see, I'm stuck on the use of my integer variable.
Here is what I have. I can successfully write the Company name but I can't get the ProcTaskName:
Private Sub Form_Close()
On Error GoTo Err_Form_Close
Dim strCompany As String
Dim sqls As String
Dim x As Integer
strCompany = Me![CoName]
'MsgBox strCompany
x = 1
sqls = "INSERT INTO Tbl_Proc(ProcCo, ProcTaskName)" & _
"VALUES ('" & strCompany & "', SELECT TaskName FROM Tbl_Task WHERE TaskNum=""" & x & """)"
DoCmd.RunSQL sqls
'This works - "VALUES ('" & strCompany & "', 'cat')"
Exit_Form_Close:
Exit Sub
Err_Form_Close:
MsgBox Err.Description
Resume Exit_Form_Close
End Sub

If I understand what you are asking correctly, you want your sql to look something like this:
INSERT INTO Tbl_Proc(ProcCo, ProcTaskName)
SELECT <yourCompanyVariable>, TaskName
FROM Tbl_Task
WHERE TaskNum=<whateverItIsYouHaveHere>
The select will return all of the tasks with your given number, each marked with your company variable. All of that will be inserted into your table.
If you can define everything you want in tbl_task easily, like where defaultTasks = 1 you can insert all of the tasks you need in one query without having to loop.

Thanks for the input man of much desired pants... :)
I added another column to Tbl_Tasks [TaskDefault] and made all values 1.
The following code works within Microsoft Access 2013 VBA module.
sqls = "INSERT INTO Tbl_Proc(ProcCo, ProcTaskName)" & _
"SELECT '" & strCompany & "', TaskName " & _
"FROM Tbl_Task WHERE TaskDefault=1"
DoCmd.RunSQL sqls

Related

Run time error 2107 after running a "DELETE .." SQL statement - VBA/MS Access

I am relatively new to Access VBA and I keep getting the run-time error 2107 on every even numbered run of the following code, and every odd numbered run runs very fine.
I have a summary form that is built to find unique course names and perform a mathematical count function according to filter criteria given by the user. The results are temporarily stored in a table Tbl_EnqSummary.
The code goes like this:
'Empty all previous records in the EnqSummary table:
DoCmd.RunSQL "DELETE * FROM Tbl_EnqSummary"
'find out unique entries in the main data table (Enquiries) and populate the Courseidentifier field in the EnqSummary table with these distinct names:
courses = "INSERT INTO Tbl_EnqSummary ( CourseIdentifier ) " _
& "SELECT DISTINCT Tbl_Enquiries.CourseEnquiryIdentifier FROM Tbl_Enquiries " _
& "WHERE ((Tbl_Enquiries.EnqDate >= #" & Format(Me.txtDateFrom.Value, "yyyy-mm-dd") & "#) " _
& "AND (Tbl_Enquiries.EnqDate <= #" & Format(Me.txtDateTo.Value, "yyyy-mm-dd") & "#)) " _
& "ORDER BY Tbl_Enquiries.CourseEnquiryIdentifier"
'Requery the form
DoCmd.RunSQL courses
summarytable = "SELECT * FROM Tbl_EnqSummary ORDER BY Tbl_EnqSummary.CourseIdentifier"
Me.RecordSource = summarytable
Me.AllowAdditions = False
Me.Requery
Here I get the run-time error 2107 stating there is some validation rule being violated. There is no validation rule anywhere - I have checked and checked.

Running an IF statement in MS VBA using a similar field from two tables

I am trying to set a quantity value based on a sum of the current quantity and then subtracting an amount based on a quantity value in another table.
My current thought process is: If QuantityA is less than or equal to Quantity B then subtract QuantityA from Quantity B.
I am no expert on SQL and MS VBA, so I was wondering how I can make an if statement with the two different tables.
Private Sub Command23_Click()
If QuantityA <= QuantityB Then
QuantityB = QuantityB - QuantityA
Else
MsgBox "You can not hire that many" & ToolName & "as there is only" & [DEPARTMENT TOOLS (stocked)].Quantity & "available"
End If
MsgBox "Your hire request has been successful"
End Sub
Any help would be appreciated
You can achieve what you're asking by opening a recordset containing the results of a query and comparing the values returned by the query. In order to restrict the query to the proper quantities you need to pass in the ID of the tool you are checking.
#June7 is correct about saving calculated data. The only time you would want to save it is if you are keeping a log of events or if speed of join queries becomes an issue (unlikely given proper DB structure)
toolId might be stored in a text box control for example
Function Something_Click(toolId as string)
Dim rs as Recordset
' create a recordset containing data from the two tables
Set rs = CurrentDB.OpenRecordset("SELECT A.TOOL_QTY AS TOOL_QTY_A, " _
& " B.TOOL_QTY AS TOOL_QTY_B, A.TOOLNAME AS TOOLNAME" _
& " FROM TABLE1 AS A " _
& " INNER JOIN TABLE2 AS B ON A.TOOL_ID = B.TOOL_ID" _
& " WHERE A.TOOL_ID = '" & toolId & "'")
' compare the values in the table
If rs![TOOL_QTY_A] <= rs![TOOL_QTY_B] Then
' your true condition, for example
' MsgBox "Success"
Else
' your false condition, for example
' MsgBox "Oops, not enough of " & rs![TOOLNAME]
End If
' close the recordset
rs.close
End Function

Execute a SQL statement inside VBA Code

I am attempting to execute a SQL query inside of VBA Code. The query works in MS Access and asks the user to input a value for Customer_Name and Part_Number
What I have done is written the VBA Code in outlook so we can run the macro to execute the query from Outlook. The code I have currently works until the very bottom line on the DoCmd.RunSQL portion. I think I have this syntax incorrect. I need to tell it to run the string of SQL listed above:
Public Sub AppendAllTables()
Part_Number = InputBox("Enter Part Number")
Customer_Name = InputBox("Enter Customer Name")
Dim strsqlQuery As String
Dim Y As String
Y = "YES, Exact Match"
Dim P As String
P = "Possible Match - Base 6"
Dim X As String
X = "*"
strsqlQuery = "SELECT Append_All_Tables.Customer,
Append_All_Tables.CustomerCode, Append_All_Tables.PartNumber,
Append_All_Tables.Description, Append_All_Tables.Vehicle, SWITCH" &
Customer_Name & " = Append_All_Tables.PartNumber, " & Y & ", LEFT(" &
Part_Number & ",12) = LEFT(Append_All_Tables.PartNumber,12)," & Y & ",
LEFT(" & Part_Number & ",6) = LEFT(Append_All_Tables.PartNumber,6)," & P
& ") AS Interchangeability FROM Append_All_Tables WHERE" & Customer_Name
& "Like " & X & Customer_Name & X & "AND
LEFT(Append_All_Tables.PartNumber,6) = LEFT(" & Part_Number & ",6);"
Set appAccess = CreateObject("Access.Application")
appAccess.OpenCurrentDatabase "path.accdb"
appAccess.DoCmd.RunSQL "strsqlQuery"
End Sub
Please note, the path has been changed for privacy. The SQL code already works in Access. I am only needing the last line to be evaluated.
If you want to have a datasheet form view show these records you can use
DoCmd.OpenForm
First create a query with the data you want to see, then bind that to your form using the Record Source property, then when you call DoCmd.OpenForm pass in the filter you want.
I'm not following what you're trying to do with SWITCH in your query (is that supposed to be the switch() function? it has no parentheses). But you'll need to adjust that to join to use a Where statement instead.
I agree with a couple of the above posts.
You need to do a Debug.Print of the strsqlQuery variable BEFORE YOU DO ANYTHING! Then evaluate that statement. Does it look right? As Matt says, it doesn't look like you have line continuations, which would make your SQL statement incomplete (and thus, the computer doesn't think its a query at all).
My personal preference is to define the SQL like you have, then create the actual query using that SQL (create query def), and then call that query, because it will now be an actual object in the database. The QUERY can show up as a datasheet without any form requirement, but a pure SQL Statement cannot.
Michael
Remove the quotes.
appAccess.DoCmd.RunSQL "strsqlQuery" to appAccess.DoCmd.RunSQL strsqlQuery

Syntax error in SQL update

I am new to both MS Access and SQL. Now I am trying to create an inventory database for our company in Ms Access. I try to extract data from the reception form to update the inventory balance. But I met a syntax error message when I executed a SQL update statement. This is weird for me because I used the same statements that successfully running in other tables. The only difference is my former successful update working by direct text replacement and my error occurring update is working in a numeric object.
Please help me to check where I am wrong.
This is my code:
Private Sub Command96_Click()
CurrentDb.Execute "UPDATE tbl_Current_Stock" & _
"SET Stock_Level= Stock_Level + " & Me!txtOrderQty & "" & _
"Where tbl_Current_Stock.Raw_Material= " & Me!cboPurchase.Column(1) & ""
End Sub
Thanks!
You need to add spaces before SET and Where. Otherwise, your command will look something like UPDATE tbl_Current_stockSET Stock_Level= Stock_Level + 3Where.....
Private Sub Command96_Click()
CurrentDb.Execute "UPDATE tbl_Current_Stock" & " " & _
"SET Stock_Level= Stock_Level + " & Me!txtOrderQty & " " & _
"Where tbl_Current_Stock.Raw_Material= " & Me!cboPurchase.Column(1) & ""
End Sub
You might also need to wrap the Raw_Material column in quotes if it is not numeric.
check your sentence correctly. there is no technical error. there are some space missing in you query.
just add white space before "SET" and "where" words.
CurrentDb.Execute "UPDATE tbl_Current_Stock" & _
" SET Stock_Level= Stock_Level + " & Me!txtOrderQty & "" & _
" Where tbl_Current_Stock.Raw_Material= " & Me!cboPurchase.Column(1) & ""
Friend, follow some tips to generate your updade correctly:
Check the spaces after concatenating your query
Be careful not to generate queries with keywords stuck together
UPDATE tableTestSET nome = 'My Name' WHERE active IS NOT NULL (wrong)
UPDATE tableTest SET name = 'My Name' WHERE active IS NOT NULL
Do not forget to use quotation marks when using strings
UPDATE tableTest SET name = My Name WHERE active IS NOT NULL (wrong)
UPDATE tableTest SET name = 'My Name' WHERE active IS NOT NULL
I hope it helps...
Good Luck!

Access VBA type mismatch

I'm creating a database for a local rental company. What I'm trying to do right now is create some code that can be periodically run to add bills to the database.
I have two tables I'm referencing here, the first is tblRental which is a table of rental units which includes rentalID's as a primary key, rental status, and the monthly rent, which is different on each unit. The other is tblTransaction which among other things includes the rentalID as a foreign key in a 1 to many relationship, and the amount for each bill which is named UnitRate. In the database rentalID and UnitRate are both set to numbers.
My code right now is
Dim maxRentalID As Integer
Dim db As Database
Dim rentID As DAO.Recordset
Dim unit As DAO.Recordset
Set db = CurrentDb
maxRentalID = Combo4.Value
For i = 1 To maxRentalID
Set rentID = db.OpenRecordset("SELECT tblRental.RentalID, tblRental.Status FROM tblRental WHERE (((tblRental.Status)='3') AND ((tblRental.RentalID)=" & i & "));")
Set unit = db.OpenRecordset("SELECT tblRental.Rentalcharge FROM tblRental WHERE (((tblRental.RentalID)=" & i & "));")
If rentID Is Not Null Then
DoCmd.RunSQL "INSERT INTO tblTransction ([RentalID], [UnitRate]) VALUES (" & rentID, unit & ");"
End If
Next
maxRentalID is obtained from a form which determines the ID of the last record so that the for loop will go through until the end.
Right now I get a type mismatch error and it tells me the problem is with rentID in the DoCmd.RunSQL line.
I'm trying to make the loop run a query, and if it's a valid result (status=3 on a RentalID that exists), insert a new record into tblTransaction with that RentalID and corresponding billing rate.
Based on what the debugger says I assume that what's happening is the SQL isn't being evaluated into a statement with the query value being assigned to the variable and it's trying to put the statement into a number field which doesn't work. I'm not sure how to make it evaluate properly however. I've tried using OpenRecordSet for that but it doesn't work.
I would do it without loop and opening recordsets:
Dim maxRentalID As Integer
maxRentalID = Combo4.Value
CurrentDb.Execute "INSERT INTO [tblTransction] ([RentalID], [UnitRate]) " & _
"SELECT [tblRental].[RentalID], [tblRental].[Rentalcharge] " & _
"FROM [tblRental] " & _
"WHERE [tblRental].[Status]='3' AND " & _
"[tblRental].[RentalID] BETWEEN 1 AND " & maxRentalID