VBA (access) set data type when creating a table - vba

I have a small problem. I have a VBA macro that creates a table. It works. But Call set data type "short text" and a need a number for column FB_average, Cil_FB and Plneni_FB.
Does anyone please have a solution tip?
Call generuj_t_vystup("t_prod_work_time_fb.Skill,t_prod_work_time_fb.Skill_KM,t_prod_work_time_fb.Locality,t_prod_work_time_fb.Team,t_prod_work_time_fb.Spv_name,t_prod_work_time_fb.Agent_name,t_prod_work_time_fb.Agent_login,t_prod_work_time_fb.Rok,t_prod_work_time_fb.Kvartal,t_prod_work_time_fb.Měsíc,t_prod_work_time_fb.Tyden,t_prod_work_time_fb.Event_date", "t_vystup_fb_denni_agent")
Public Function generuj_t_vystup(hlavicka As String, vystupni_tabulka As String)
SQL = "Select "
SQL = SQL & hlavicka & ", "
SQL = SQL & "Nz(SUM([Feedback_summary])) AS FB_summary,"
SQL = SQL & " Nz(SUM([Feedback_count])) AS FB_count,"
SQL = SQL & " Nz(SUM([Feedback_summary])/SUM([Feedback_count])) AS FB_average,"
SQL = SQL & " Nz(SUM([Feedback_summary])/SUM([Feedback_count])) AS Cil_FB,"
SQL = SQL & " Nz(SUM([Feedback_summary])/SUM([Feedback_count])) AS Plneni_FB"
SQL = SQL & " INTO "
SQL = SQL & vystupni_tabulka
SQL = SQL & " FROM t_prod_work_time_fb "
SQL = SQL & " GROUP BY "
SQL = SQL & hlavicka
spustsql SQL
End Function
Sub spustsql(SQL As Variant)
On Error GoTo chyba
DoCmd.RunSQL SQL
Exit Sub
Thanks a lot.

Set a numeric value (0) to replace Null:
SQL = SQL & " Nz(SUM([Feedback_summary]), 0) AS FB_summary,"
SQL = SQL & " Nz(SUM([Feedback_count]), 0) AS FB_count,"
SQL = SQL & " Nz(SUM([Feedback_summary])/SUM([Feedback_count]), 0) AS FB_average,"
SQL = SQL & " Nz(SUM([Feedback_summary])/SUM([Feedback_count]), 0) AS Cil_FB,"
SQL = SQL & " Nz(SUM([Feedback_summary])/SUM([Feedback_count]), 0) AS Plneni_FB"

Related

How do I concatenate a variable of the type Date/Time in my Insert statement

This runs when the form loads:
Private Sub Form_Load()
TempVars("F_ID") = txtF_SNr.Value
TempVars("Status") = txtStatus.Value
TempVars("seit") = txtSeit.Value
TempVars("bis") = txtBis.Value
TempVars("von") = txtVon.Value
TempVars("an") = txtAn.Value
TempVars("Bemerkung") = txtBemerkung.Value
End Sub
txtSeit is the name of the text field in my form, bound to the column [seit] with the type of Date/Time in my table.
sql = "Insert into tblStatusFahrzeugeHistory (F_ID, Status, seit, bis, von, an, Bemerkung, Datenbank_Nutzer, Eintrag_erstellt_am, Eintrag_erstellt_um)" & _
"Select tblStatusFahrzeuge.F_ID, tblStatusFahrzeuge.Status, tblStatusFahrzeuge.seit, tblStatusFahrzeuge.bis, tblStatusFahrzeuge.von, tblStatusFahrzeuge.an, tblStatusFahrzeuge.Bemerkung, tblStatusFahrzeuge.Datenbank_Nutzer, tblStatusFahrzeuge.Eintrag_erstellt_am, tblStatusFahrzeuge.Eintrag_erstellt_um " & _
"From tblStatusFahrzeuge Where ( " & txtSeit.Value & " <> seit AND [F_ID] = '" & Me.txtF_SNr.Value & "') "
The sql statement above gives me the error:
runtime error: '3075' syntax error in number in query expression...
How do I concatenate txtSeit.Value correctly? (Sorry im a beginner!)

VB 6 application throwing error The server principal (username) unable to access the database production under the current security context

I am working with a legacy application that was written in vb 6. In the code there is an embedded sql query. I am trying to make a left join on another database. using the following select statement:
SQL = "select h.case_ref, t.t5_desc, h.narisno, h.valuation_ref, h.claimant, h.t5," & _
" h.claim_amount, h.claim_date , h.dateofentry, h.case_completed, l.project_short_name AS narisno_desc, h.case_type "
If blnFromCaseRefSelection = True Then
SQL = SQL & " from case_header h left join lut_t5 t on h.t5 = t.t5 left join" & _
" [production].[dbo].[xxx_01_project_attributes] l on h.nno = l.pin where h.case_ref = '" & cboCaseRef.Text & "'"
Else
SQL = SQL & " from lut_fileref f, case_header h left join lut_t5 t on h.t5 = t.t5" & _
" left join lut_nno n on h.nno = n.nno Where h.case_ref = f.case_ref" & _
" and f.ha_fileref = '" & xxoHAFileRef.Text & "'"
End If
error : The server principal (username) unable to access the database
production under the current security context
Any idea of how ui can solve this, my experience with VB 6 is basic

Not match the datatypes of the criteria expression ms access

I have a update like this in a module of ms access:
sql = "ALTER TABLE Carrera "
sql = sql & "ADD COLUMN carrera_nombre TEXT(25);"
Application.CurrentDb.Execute (sql)
sql = "UPDATE Carrera "
sql = sql & "SET Carrera.[carrera_nombre] = '" & strFunction(Carrera.[NombreCarrera]) & "' "
sql = sql & "WHERE Carrera.[CarreraId] > 1000;"
Application.CurrentDb.Execute (sql)
In database the column NombreCarrera exist, and I declared the function:
Function strFunction(str) As String
strFunction = str & "test"
End Function
But I get the error 3464 Not match the datatypes of the criteria expression, and I don't understand why, the strFunction return a String and the carrera_nombre and CarreraNombre columns type is TEXT.
EDIT: If I check string sql through MsgBox(sql) y get the right query: UPDATE Carrera SET Carrera.[carrera_nombre] = 'mathtest' WHERE Carrera.[CarreraId] > 1000;
I believe since you declare the sql command as a string, you will have to get it first.
so one of your code
sql = sql & "SET Carrera.[carrera_nombre] = strFunction(Carrera.[NombreCarrera])"
Should become
sql = sql & "SET Carrera.[carrera_nombre] = " & strFunction(Carrera.[NombreCarrera]) & """

Microsoft Access run-time error '3075' Syntax Error

I want to delete something in my database using a button with the following VBA behind it.
Unfortunately it gives me a run-time error and I don't know why. I've looked how Access give the SQL statement back and in SQL Server it gives me no errors.
VBA:
Private Sub btnDeleteTaak_Click()
If Not IsNull(Me.lstTaakMonteur) Then
If Not IsNull(Me.comboMonteur.Value) Then
If Not IsNull(Me.comboOpdracht.Value) Then
Dim DeleteSQL As String
DeleteSQL = "DELETE OpdrachtTaak WHERE opdrachtnr = " & Me.comboOpdracht.Value & " AND taaknr = " & Me.lstTaakMonteur.Value & " AND monteurcode = '" & Me.comboMonteur.Value & "'"
DoCmd.RunSQL (DeleteSQL)
Me.lstTaakMonteur.Requery
Else
MsgBox ("Er is geen opdracht geselecteerd")
End If
Else
MsgBox ("Er is geen monteur geselecteerd")
End If
Else
MsgBox ("Er is geen taak geselecteerd")
End If
End Sub
The error:
Syntax error (missing operator) in query expression 'OpdrachtTaak WHERE opdrachtnr = 1 AND taaknr = 6 AND monteurcode = 'LM1"
Table structure OpdrachtTaak:
opdrachtnr NUMERIC(5) <pk,fk2> NOT NULL
taaknr NUMERIC(3) <pk, fk3> NOT NULL
tijdsduur NUMERIC(4,1) NULL
Monteurcode VARCHAR(3) <fk1> NULL
Would be great if you can help me out.
Delete statements in MS Access databases is fairly different from those in SQL Server.
In MS Access you must include From statement in your delete query. So your code will be:
DeleteSQL = "DELETE * FROM OpdrachtTaak WHERE opdrachtnr = " & Me.comboOpdracht.Value & " AND taaknr = " & Me.lstTaakMonteur.Value & " AND monteurcode = '" & Me.comboMonteur.Value & "'"

If/Then in SQL Embedded in VBA

I've got a string like this in my Excel VBA:
strSQL = "SELECT * FROM Total WHERE (SimulationID = (" & TextBox1.Text & ") And Test1 = (" & Example & "))"
However, sometimes Test will be 'is null', which makes the query
And Example = is NULL
How can I change it to add an if/then statement or something to make it say
And Example is null
when Example has a value of "is null"?
I would suggest doing the NULL comparison before assembling the SQL statement strSQL.
If you check for the value of Example beforehand, you can alter your strSQL statement accordingly based on that check.
EDIT:
In response to Daniel's first and second comment below, I still would prefer the following over doing it inline:
Dim strSqlTail
strSqlTail = ""
If (Example1 = Null) Then strSqlTail = "AND Example1 IS NULL"
If (Example2 = Null) Then strSqlTail = strSqlTail & "AND Example2 IS NULL"
If (Example3 = Null) Then strSqlTail = strSqlTail & "AND Example3 IS NULL"
...
Note: The strSqlTail can be whatever SQL would make your situation work since I don't quite understand what is being queried from the sample.
You just create a function that puts the equal sign and space before the number if it doesn't equal "is null", and modify the string assignment statement appropriately, like so:
Public Function NullModString(Example As String) As String
If Example <> "is null" Then Example = "= " & Example
NullModString = Example
End Function
strSQL = "SELECT * FROM Total WHERE SimulationID = " & TextBox1.Text & _
"And Test1 " & NullModString(Example)
Note, that I didn't understand why the extra parentheses were in there, but it would be simple to put them back in.
One solution is to coalesce out the null using a Coalesce function (or if using Access, the Nz function) :
trSQL = "SELECT ..." & _
" FROM Total" & _
" WHERE SimulationID = " & TextBox1.Text & " & _
" And Coalesce(Test1,"""") = "" & Example & """
A better way would be to dynamically include or not include the entire And statement based on whether Example had a value or to substitute Test Is Null when Example did not have a value. So something akin to:
Dim testElements() As Variant
Dim vElement As Variant
Redim testElements(6,1)
testElements(0,0) = Example1
testElements(0,1) = "Test1"
testElements(1,0) = Example2
testElements(1,1) = "Test2"
...
Dim elementIndex as Integer
Dim colName As String
Dim elementValue As Variant
For elementIndex = 0 To UBound(testElements)
elementValue = testElement(elementIndex, 0)
colName = testElement(elementIndex, 1)
If Len(Nz(elementValue)) = 0 Then
trSQL = trSQL & " And " & colName & " = """ & Example1 & """
Else
trSQL = trSQL & " And " & colName & " Is Null"
End If
Next
First, don't embed SQL in VBA: hard to maintain, SQL injection, etc. Use a stored proc on the database side (even Access has PROCEDUREs).
Second, use COALESCE (or equivalent logic) to handle your 'empty string equates to NULL' UI logic. You don't say which SQL syntax and you haven't posted schema DLL so we're merely guessing...
SQL Server:
CREATE PROCEDURE GetTotals
#SimulationID INTEGER,
#Test1 VARCHAR(20) = NULL
AS
SELECT *
FROM Total AS T1.
WHERE T1.SimulationID = #SimulationID
AND COALESCE(T1.Test1, '') = COALESCE(#Test1, '');
Access Database Engine (a.k.a. Jet):
CREATE PROCEDURE GetTotals
(
:SimulationID INTEGER,
:Test1 VARCHAR(20) = NULL
)
AS
SELECT *
FROM Total AS T1
WHERE T1.SimulationID = :SimulationID
AND IIF(T1.Test1 IS NULL, '', T1.Test1)
= IIF(:Test1 IS NULL, '', :Test1);
Then execute the proc using your middleware (ADO, DAO, etc) with Parameter objects, using the empty string (or other 'magic' value) for NULL.