I have a subform set to the datasheet view, that I am trying to update with data from SQL Server, based on parameters specified by the users selection.
I usually achieve this with stored procedures and have the VBA call them through ADO, but this data is different in that the RecordSource needs to be able to be amended/edited directly within the data table.
I have a data table that I currently use to display data and this uses the below code:
Dim db As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sp As ADODB.Command
Set db = New ADODB.Connection
Set rs = New ADODB.Recordset
Set sp = New ADODB.Command
Set ps = frmName
db.Open dbString
db.CursorLocation = adUseClient
With sp
.ActiveConnection = db
.CommandText = "x04_ch_sl_ptsTable"
.CommandType = adCmdStoredProc
.Parameters.Append sp.CreateParameter("@tmName", adVarChar, adParamInput, 4, tmName)
End With
sp.Parameters.Append sp.CreateParameter("@wkEnd", adDBTimeStamp, adParamInput, , wkEnd)
Set rs = sp.Execute
Set ps.subFormDataViewer.Form.Recordset = rs
Exit Sub
End If
db.Close
Can this be amended to make the dataset updateable?
This is so far the only way I have been able to achieve what I want to do, but due to the majorly obvious security and injection issues, I do not want to go down this route:
ps.subFormDataViewer.Form.RecordSource = " SELECT p.ps_dateClaim as [Date], p.ps_id as [ID], p.ps_empid as [Employee ID], e.hc_fullName as [Employee], p.ps_pts as [Claimed] " & _
" FROM (([ODBC;DRIVER=SQL Server;SERVER=<REDACTED>;Integrated_Security=SSPI;DATABASE=<REDACTED>].prod_pts as p " & _
" INNER JOIN [ODBC;DRIVER=SQL Server;SERVER=<REDACTED>;Integrated_Security=SSPI;DATABASE=<REDACTED>].hc_employee as e " & _
" ON p.ps_empid = e.hc_empid) " & _
" WHERE (p.ps_dateClaim = #" & wkEnd & "#" & _
" AND (e.hc_teamName = '" & tmName & "'); "
I have tried the following ADO methods with no success:
With sp
Set .ActiveConnection = db
.CommandText = " SELECT t.Date, t.TeamName, t.Reference, t.Status, t.Reason, t.Checked " & _
" FROM testTbl as t" & _
" WHERE t.TeamName = @tmName "
.Parameters.Append .CreateParameter(, adVarChar, adParamInput, 4, tm)
Set rs = .Execute
End With
With sp
Set .ActiveConnection = db
.CommandText = " SELECT t.Date, t.TeamName, t.Reference, t.Status, t.Reason, t.Checked " & _
" FROM testTbl as t" & _
" WHERE t.TeamName = ? "
Set rs = .Execute(, Array(tm))
End With
(the 2nd example does produce data, but the recordset is not updateable as it recognises each field as an "expression")
I have been able to achieve this with DAO:
Dim db as DAO.Database
Dim rs as DAO.Recordset
Dim qd as DAO.QueryDef
Dim dbSQL as string
dbSQL = " SELECT t.Date, t.TeamName, t.Reference, t.Status, t.Reason, t.Checked " & _
" FROM testTbl as t" & _
" WHERE t.TeamName = tmName1 "
Set qd = db.CreateQueryDef("", dbSQL)
With qd
.Parameters!tmName1 = tm
End With
Set rs = qd.OpenRecordset
Set ps.subFormDataViewer.Form.Recordset = rs