How can I use values from a form's input fields in an INSERT query? - forms

I have a form for adding a customer into a table, and I'm trying to write the query for it. I'm having trouble getting the values from the form's input fields (name, address etc.) and putting it into the query.
How can I do this?

You can refer to the controls on the form or the fields in the recordset. They may or may not have the same values depending on whether the form is dirty or not.
A simple query might be 9query design window)
UPDATE ATable SET AName=Forms!Form1!txtName
INSERT INTO ATable ( AName ) Values ( Forms!Form1!txtName )
In the code belonging to the form you could say
Dim db As Database
Set db = CurrentDB
sSQL = "UPDATE ATable SET AName='" & Replace(Forms!Form1!txtName,"'","''") & "'"
db.Execute sSQL, dbFailOnError
sSQL = "INSERT INTO ATable ( AName ) Values ('" _
& Replace(Forms!Form1!txtName,"'","''") & "')"
db.Execute sSQL, dbFailOnError

Related

How can I avoid duplicates insert of records from datagridview to SQL Server table

I have a table in SQL Server 2008 R2 where I have a table CT11. What I want is to stop inserting duplicates records in the table using cellendedit event. How can I do it because I am getting duplicates of records?
Private Sub DataGridView1_CellEndEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellEndEdit
For Each row In DataGridView1.Rows
If cmbexam.Text = "CAT 1" Then
sqlSTR = "INSERT INTO CT11 (Admno, Name, Score) VALUES ('" & row.Cells(0).Value & "','" & row.Cells(1).Value & "','" & row.Cells(2).Value & "')"
ExecuteSQLQuery(sqlSTR)
End If
Next
End Sub
First, learn how to use SQL Command
How to use parameters "#" in an SQL command in VB
If you want the database to validate your entry then learn how to use Stored Procedure
https://mostafaelmasry.com/2015/10/03/creating-system-stored-procedure-in-sql-server-2008-r2/
In Stored Procedure add a condition that will check your entry ex;
SELECT #record = COUNT(1) FROM CT11
WHERE Admno = #Admno AND Name = #Name AND Score = #Score;
IF #record = 0
BEGIN
INSERT INTO CT11 (Admno, Name, Score) VALUES (#Admno, #Name, #Score);
END
In VB
For Each row In DataGridView1.Rows
If cmbexam.Text = "CAT 1" Then
MyCommand = New SqlCommand("StoredProcedureName", dbConn)
MyCommand.CommandType = CommandType.StoredProcedure
MyCommand.Parameters.AddWithValue("#Admno", row.Cells(0).Value)
MyCommand.Parameters.AddWithValue("#Name", row.Cells(1).Value)
MyCommand.Parameters.AddWithValue("#Score", row.Cells(2).Value)
MyCommand.ExecuteNonQuery()
End If
Next
Or follow this thread: SQL Server stored procedure and execute in VB.NET
Or you can use VB to validate the values by executing a select statement and check if there a record or not.

Access pass-through query with parameters not updating with prompted parameters

An Access pass-through query works when using the default parameters. When used in an Access report, the prompts that are used returns records based on the default parameters in the ptq and not the answered prompts. Default data is being returned.
I have a SQL Server based stored procedure that works, uspWorkCentreReport, that uses #TheDate DATE, #WC VARCHAR(15), #Shift INT for parameters and returns, through a SELECT statement, these columns:
[JOB NUMBER], [REL #], [JOB NAME], QTY.
Here's the ALTER line of the stored procedure code:
ALTER PROCEDURE [dbo].[uspWorkCentreReport]
#TheDate DATE,
#WC VARCHAR(15),
#Shift INT
The Access pass-through query, ptq_uspWorkCentreReport, passes these default parameters '2019-05-30','PCOT',1 and uses a DSN-less ODBC connection that works to return default data. I forgot to try but I think it will return correct data with whatever default parameters I use to replace '2019-05-30','PCOT',1. EDIT - I tried it this morning and indeed any appropriate replacement parameters return the appropriate associated records. Here's the ptq's one line:
exec uspWorkCentreReport '2019-05-30','PCOT',1
I provide the ptq with default parameters based on Albert D. Kallal's SO reply.
I use an Access select query, qry_ptq_uspWorkCentreReport, to receive [JOB NUMBER],[REL #],[JOB NAME],QTY and pass the parameters TheDate, set to Date With Time, WC, set to Short Text, and Shift, set to Integer.
qry_ptq_uspWorkCentreReport uses the pass-through query. The parameters are set using Access' Parameters applet and not within the query fields. Running this select query prompts for the 3 parameters but only returns data based on the default parameters set in the ptq's one line. I did not think to look at the Access SQL statement but will do so when I get to work tomorrow morning. EDIT - Here's the SQL statement for qry_ptq_uspWorkCentreReport:
PARAMETERS TheDate DateTime, WC Text ( 255 ), Shift Short;
SELECT ptq_uspWorkCentreReport.[JOB NUMBER], ptq_uspWorkCentreReport.[REL #], ptq_uspWorkCentreReport.[JOB NAME], ptq_uspWorkCentreReport.QTY
FROM ptq_uspWorkCentreReport;
Of course the above three functions culminate in an Access report, rpt_qry_ptq_WorkCentreReport to make the records human readable.
I have used the same scenario for another report the takes From and To dates as parameters. When that report runs, the prompts take the dates and return records based on those dates and not the dates in the ptq. Here's that ptq:
exec uspMergeAandPJobs '2018-01-01','2019-01-01'
Indeed, I tried using
exec uspMergeAandPJobs '',''
And the report returns 0 records!
Not sure what I am missing and would appreciate any feedback. TIA.
I tried the following with the help of a tutor:
Sub Report_Load()
Dim strFromDate As String
Dim strToDate As String
Dim strWC As String
Dim intShift As Integer
Dim strSQL As String
strFromDate = InputBox("From Date and Time: ")
strToDate = InputBox("Enter To Date and Time: ")
strWC = InputBox("Enter Work Center: ")
intShift = InputBox("Enter Shift: ")
Dim qdf As DAO.QueryDef, rst As DAO.Recordset
Set qdf = CurrentDb.CreateQueryDef("")
qdf.SQL = "exec dbo.uspWorkCentreReport " & "'" & strFromDate & "', " & "'" & strToDate & "', " & "'" & strWC & "', " & intShift & ";"
qdf.Connect = "ODBC;DRIVER=ODBC Driver 13 for SQL Server;SERVER=OURS\NTSQL;Trusted_Connection=Yes;DATABASE=TablesCoE;ApplicationIntent=READONLY;"
qdf.ReturnsRecords = True
Set rst = qdf.OpenRecordset
rst.Close
Set rst = Nothing
Set qdf = Nothing
End Sub
After the prompts VBA spits up a Run-Time error 3129 - Invalid SQL statement; expected 'DELETE', 'INSERT', 'PROCEDURE', 'SELECT', or 'UPDATE'. Neither of us were able to determine what was causing the error. In VBA the "qdf.SQL..." line is highlighted in yellow.
EDIT - Adding stored proc's SQL code:
ALTER PROCEDURE [dbo].[uspWorkCentreReport_TEST] #FromDate DATETIME,#ToDate DATETIME,#WC VARCHAR(15),#Shift INT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Build table variable SumTable structure
DECLARE #SumTable TABLE(matl_nbr VARCHAR(60),QTY DECIMAL(4,0),matl_dsc VARCHAR(50))
-- P jobs and their summed WorkCentre traversals using crosstab - each traversal is added up
INSERT INTO #SumTable(matl_nbr,matl_dsc,QTY)
SELECT SRC1.matl_nbr,SRC1.matl_dsc,
SUM(CASE WHEN SRC1.locn_to = #WC THEN 1 ELSE 0 END) AS QTY
FROM
(
SELECT matl_nbr,matl_dsc,locn_to
FROM mtrk_CompanyE.dbo.trxn_hstd th
WHERE (last_upd >= #FromDate AND last_upd <= #ToDate) AND
locn_to = #WC
)SRC1
GROUP BY matl_nbr,matl_dsc
-- These updates take all the summed WorkCentre (locn_to) columns and turn each into "1" for later summing
UPDATE #SumTable
SET QTY = 1
WHERE QTY >1
-- Shortening the material number from 123456_00_00_R1_00 to 1234560
UPDATE #SumTable
SET matl_nbr = LEFT(matl_nbr,6) + right(LEFT(matl_nbr,9),1)
SELECT LEFT(A.matl_nbr,6)[JOB NUMBER],SUBSTRING(A.matl_nbr,7,1)[REL #],matl_dsc AS [JOB NAME],QTY
FROM (SELECT matl_nbr,matl_dsc,
SUM(CASE WHEN QTY = 1 THEN 1 ELSE NULL END) AS QTY
FROM #SumTable
GROUP BY matl_nbr,matl_dsc)A
ORDER BY QTY DESC;
END
EDIT - Finished sub:
Private Sub Report_Open(Cancel As Integer)
Dim strFromDate As String
Dim strToDate As String
Dim strWC As String
Dim intShift As Integer
Dim strSQL As String
strFromDate = InputBox("Enter From Date and Time: ")
strToDate = InputBox("Enter To Date and Time: ")
strWC = InputBox("Enter Work Center: ")
intShift = InputBox("Enter Shift: ")
strSQL = "exec dbo.uspWorkCentreReport_TEST " & "'" & strFromDate & "', " & "'" & strToDate & "', " & "'" & strWC & "', " & intShift & ";"
CurrentDb.QueryDefs("ptq_uspWorkCentreReport").SQL = strSQL
DoCmd.OpenReport "rpt_qry_ptq_uspWorkCentreReport", acViewReport
Me.lblFromDate.Caption = strFromDate
Me.lblToDate.Caption = strToDate
Me.lblWC.Caption = strWC
Me.lblShift.Caption = intShift
End Sub
Your Access query has parameters:
PARAMETERS TheDate DateTime, WC Text ( 255 ), Shift Short;
and since they are defined in the query definition, Access asks for them when opening/running the query.
But these parameters are never used!
There is no way for Access to pass these parameters into the pass-through query that is the basis of the Access query. Again, a PT query is nothing more than a Connect string and a constant SQL string.
So when you run the Access query, it will always run the saved contents of the PT query, i.e.
exec uspWorkCentreReport '2019-05-30','PCOT',1
The parameters you entered are ignored.
What you need to do (as outlined in the answer you refer to):
create a form to collect the parameter values
dynamically create the SQL string for the PT query with VBA
assign that SQL to the PT query:
CurrentDb.QueryDefs("ptq_uspWorkCentreReport").SQL = strSql
(it is automatically saved)
and then you can run the report based on the Access query - or better: directly use the PT query as record source for the report.
Remove the parameters from the Access query, they are of no use for your situation. Or remove the query entirely, unless you need it to join the PT query with something else.
Edit for above edit:
If you get a runtime error, there is probably a syntax error in your .Sql. Build the SQL string in a variable, do Debug.Print strSql, and run that string in SSMS. You may need to change date formatting (depending on your locale settings).
Also: See my 3rd bullet. Defining a temporary querydef and opening a recordset doesn't work for a report. You must assign the .Sql of the existing query that is the record source of the report.
Addendum: if you need to create a new query, first set .Connect, and then .Sql, so Access knows it's a Pass-Through query.
Access SQL doesn't know exec.
Edit 2
You have an existing, working PT query ptq_uspWorkCentreReport, which returns records for one set of parameters, e.g.
exec uspWorkCentreReport '2019-05-30','PCOT',1
Use this query as record source for your report.
To run the report with different parameters, you must modify the query's SQL. You can do this manually in query design view, or with VBA.
I think Report_Load() is too late for modifying its record source (the PT query). Run the following sub, then open the Report.
Sub SetUspParameters()
Dim strFromDate As String
Dim strToDate As String
Dim strWC As String
Dim intShift As Integer
Dim strSQL As String
strFromDate = InputBox("From Date and Time: ")
strToDate = InputBox("Enter To Date and Time: ")
strWC = InputBox("Enter Work Center: ")
intShift = InputBox("Enter Shift: ")
strSQL = "exec dbo.uspWorkCentreReport " & "'" & strFromDate & "', " & "'" & strToDate & "', " & "'" & strWC & "', " & intShift & ";"
Debug.Print strSQL
' This line is all that's needed to modify the PT query
CurrentDb.QueryDefs("ptq_uspWorkCentreReport").SQL = strSQL
End Sub
In practice, you don't want to use 4 x InputBox, but a form.

Access Form / VBA: Concatenated Field Name

I created a Form in Access, and within this form there is a button which will allow the user to insert a record into a table ("Tbl")
The format of this table is:
Report1_Field1
Report1_Field2
Report2_Field1
Report2_Field2 (and so on)
The Form will ask the user to:
- Select the report name ("ReportName"); which could be "Report1" or "Report2"
- Input a value for Field1 and Field2
The VBA code behind the button is as follows:
Private Sub ButtonUpdate
Dim NameReport as String
Dim FirstField as String
Dim SecondField as String
NameReport = ReportName
FirstField = ReportName & "_Field1"
SecondField = ReportName & "_Field2"
DoCmd.RunSQL "INSERT INTO tbl (FirstField, SecondField) VALUES (Field1, Field2)"
End Sub
I am however getting the Run-Time error 3127: The INSERT INTO statement contains the following unknown field name: 'FirstField'. Make sure you have typed the name correctly, and try the operations again.
Thoughts?
The SQL string is reading "FirstField" and "SecondField" as literal text instead of using your variables. Try this:
DoCmd.RunSQL "INSERT INTO tbl (" & FirstField & ", " & SecondField & ") VALUES (Field1, Field2)"

Add Form Information to a Table

Option Compare Database
Private Sub cmdAdd_Click()
CurrentDb.Execute "INSERT INTO Overtime(Todays_Date, Employee_Name, " & _
"Start_Date, End_Date,Comments) " & _
" VALUES(" & Me.txtCurrentday & ",'" & Me.txtName & "','" & _
Me.txtBegin & "','" & Me.txtEnd & "','" & Me.txtComment & "')"
Me.Refreshenter
cmdClear_Click
End Sub
Private Sub cmdClear_Click()
Me.txtCurrentday = ""
Me.txtName = ""
Me.txtBegin = ""
Me.txtEnd = ""
Me.txtComment = ""
Me.txtCurrentday.SetFocus
End Sub
Private Sub cmdClose_Click()
DoCmd.Close
End Sub
Hello, I have created a Form and a Table in Microsoft Access 2010. The Form is called pbicovertime it has five unbound text boxes which all have unique names and three buttons. I would like the information that has been entered in the Form to be added to the Table called Overtime when the Add button is pressed. The code above does add the data from the Form to the table, however I get a Run-timer error '3061": Too few parameters. Expected 1 error message after closing and reopening the database. So initially everything seemed to be working fine. All the information entered in the Form was being added to the correct column in my Overtime Table. The issue took place after closing and reopening the database. I am not really sure how to proceed from this point.
FYI this is my first time working with Forms in Access !
Open your table as a recordset and add a row. That will avoid complications based on required/missing quotes or date delimiters in the values you're adding.
Option Compare Database
Option Explicit ' <- add this
Private Sub cmdAdd_Click()
Dim db As DAO.database
Dim rs As DAO.Recordset
Set db = CurrentDb
Set rs = db.OpenRecordset("Overtime", dbOpenTable, dbAppendOnly)
With rs
.AddNew
!Todays_Date = Me.txtCurrentday
!Employee_Name = Me.txtName
!Start_Date = Me.txtBegin
!End_Date = Me.txtEnd
!Comments = Me.txtComment
.Update
.Close
End With
'Me.Refreshenter ' <- what is this?
cmdClear_Click
End Sub
If the original missing parameter error was because of a misspelled field name, this code will throw an error on one of the lines between AddNew and Update, so you should be able to quickly identify which name is misspelled.
Note: Always include Option Explicit in the Declarations sections of your code modules. And then run Debug->Compile from the VB Editor's main menu. Correct anything the compiler complains about before you spend time troubleshooting the code.
I don't know what Me.Refreshenter is. It looks like a misspelling of Me.Refresh. If so, that is something Option Explicit will warn you about. However, if you wanted Refresh, I suggest you substitute Me.Requery. The reason is that Refresh will pull in changes to any of the existing rows in the form's recordset, but not newly added rows. Requery gets new rows in addition to changes to existing rows.
I'm willing to bet it's this line that it's crashing on.
CurrentDb.Execute "INSERT INTO Overtime(Todays_Date, Employee_Name, " & _
"Start_Date, End_Date,Comments) " & _
" VALUES(" & Me.txtCurrentday & ",'" & Me.txtName & "','" & _
Me.txtBegin & "','" & Me.txtEnd & "','" & Me.txtComment & "')"
Specifically the Me.txtCurrentday, because it will be evaluated as straight text, and depending on how your PC is setup, it may be confusing SQL. e.g., it might look like this:
INSERT INTO Overtime(Todays_Date, Employee_Name, Start_Date, End_Date,Comments)
VALUES ( Dec 1, 2013, 'JoeSmith', 'Jan 1, 2013', 'Dec 31, 2013',
'Some important comment');
Dates you should encompass in #'s:
INSERT INTO Overtime(Todays_Date, Employee_Name, Start_Date, End_Date,Comments)
VALUES ( #Dec 1, 2013#, 'JoeSmith', #Jan 1, 2013#, #Dec 31, 2013#,
'Some important comment');
and it will go smoother. Also building up the SQL that way leaves you vulnerable to injections (either as an attack or error). Imagine if the comment was "This is Susie's Job", in which case that extra apostrophe would mess up the insert.

Access 2010 - Cannot edit textbox in unbound form which is populated by recordset

I am using Access 2010 with linked tables from SQL Server 2008. I have a form that I am populating using a recordset and the control source of the textbox in this form is set to a field from the recordset. I find that although I can navigate through all the 16 records on the form, and the form loads correctly, I am unable to edit the Notes text box. It needs to be editable. The textbox has Enabled=True and Locked=False. The AllowEdits property of the form is set to true. All the tables in the query have primary keys. So, is it my query then - since it has right and inner joins in it? So the issue is that I cannot type in the textbox.
Just a little background, I tried using a query as the recordsource for this form, but found that Access' AutoSave feature inserted incomplete records into my Result table, in addition to the updates and inserts done by my Save button event. If the only way to circumvent this is to ask the user whether he/she would like to save changes every time he navigates, then that would be way too frustrating for the end user. So, I have had to use an unbound form where I use VBA to populate it using a ADO recordset.
Incidentally, I can edit the DocID and DocumentType columns, it's the fields from the query that cannot be changed (QCNote)
Here is the code from my Form_Open event. I also have a Form_Current event that disables the Submit button for inapplicable categories.
Private Sub Form_Open(Cancel As Integer)
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Set cn = CurrentProject.AccessConnection
Set rs = New ADODB.Recordset
With rs
Set .ActiveConnection = cn
DocID = [Forms]![QCDocAttributes]![DocID]
DocumentType = [Forms]![QCDocAttributes]![Document Type]
strSQL = "SELECT " & DocID & " AS DocID,'" & DocumentType & "' AS DocumentType, QC_QCDecisionPoint.Description, QC_QCDecisionPoint.QCDecisionPointID , QC_QCResultDecisionPoint.QCNote FROM QC_QCResultDecisionPoint RIGHT JOIN ((QC_QCAttribute INNER JOIN QC_QCAttributeDecisionPointAsc ON QC_QCAttribute.QCAttributeID = QC_QCAttributeDecisionPointAsc.QCAttributeID) INNER JOIN QC_QCDecisionPoint ON QC_QCAttributeDecisionPointAsc.QCDecisionPointID = QC_QCDecisionPoint.QCDecisionPointID) ON QC_QCResultDecisionPoint.QCDecisionPointID = QC_QCDecisionPoint.QCDecisionPointID WHERE (((QC_QCAttribute.Description)= '" & [Forms]![QCDocAttributes]![AttributesDropdown] & "' ));"
.Source = strSQL
.LockType = adLockOptimistic
.CursorType = adOpenKeyset
.Open
End With
Set Me.Recordset = rs
Set rs = Nothing
Set cn = Nothing
End Sub