Access 2010 VBA SQL INSERT with multiple SELECT - sql

The following Code prompts out with, according to google, a kind of random/default error that doenst really lead to the problem. (Query input must contain at least one table or query)
Private Sub ButtonInsertUntergruppe_Click()
Dim sql As String
sql = "INSERT INTO tblArbeitsschritte (Auftrag_FK, Prozesspunkt_FK, Prozesspunkt) " & _
"VALUES (" & _
Forms!frm_GUI!ID_Auftraege & _
", " & _
"(SELECT ID_Prozesspunkt " & _
"FROM tblProzesspunkt " & _
"WHERE Untergruppe_FK = " & _
Me.cbUntergruppe.Column(0) & _
") , " & _
"(SELECT Prozesspunkt " & _
"FROM tblProzesspunkt " & _
"WHERE Untergruppe_FK = " & _
Me.cbUntergruppe.Column(0) & _
"));"
Debug.Print sql
CurrentDb.Execute sql, dbFailOnError
End Sub
This is what the debugger gives me:
INSERT INTO tblArbeitsschritt
(
Auftrag_FK, Prozesspunkt_FK, Prozesspunkt
)
VALUES
(
1,
(SELECT ID_Prozesspunkt
FROM tblProzesspunkt
WHERE Untergruppe_FK = 1)
,
(SELECT Prozesspunkt
FROM tblProzesspunkt
WHERE Untergruppe_FK = 1)
);

Not sure if that syntax is supported. Personally I would do:
INSERT INTO tblArbeitsschritt
(
Auftrag_FK, Prozesspunkt_FK, Prozesspunkt
)
SELECT 1, ID_Prozesspunkt, Prozesspunkt
FROM tblProzesspunkt
WHERE Untergruppe_FK = 1

Related

VB for MS Access not working when using INNER JOIN

The code isn't working properly, getting a Syntax error in INSERT INTO statement error. Trying to insert data with an inner join from an MS Access form where the user types in responses and selects a button to add the detail to a new table. Based on the information provided I want it to insert the data into another table where it is joined by a table to get the fiscal data.
stSQL = "INSERT INTO PO_Information " & _
"(Partner, PO_Number, PO_Title, Cost_Center, Description, Line_1_Amt, Line_2_Amt, Date_Added, Month_Added, Year_Added, FY, Qtr, FY_Qtr, FW, FWeek)" & _
"Select New_PO_Information.Partner, " & _
"New_PO_Information.PO_Number, " & _
"New_PO_Information.PO_Title, " & _
"New_PO_Information.Cost_Center, " & _
"New_PO_Information.Description, " & _
"New_PO_Information.Line_1_Amt, " & _
"New_PO_Information.Line_2_Amt, " & _
"New_PO_Information.Date_Added, " & _
"New_PO_Information.Month_Added, " & _
"New_PO_Information.Year_Added, " & _
"Fiscal_Calendar.FY, " & _
"Fiscal_Calendar.Qtr, " & _
"Fiscal_Calendar.FY_Qtr, " & _
"Fiscal_Calendar.FW, " & _
"Fiscal_Calendar.FWeek, " & _
"From New_PO_Information INNER JOIN Fiscal_Calendar " & _
"ON New_PO_Information.Date_Added = Fiscal_Calendar.Calendar"
stSQL = stSQL & _
"From New_PO_Information " & _
"Where ((New_PO_Information.Partner)<>'') " & _
"AND ((New_PO_Information.PO_Number)<>'') " & _
"AND ((New_PO_Information.PO_Title)<>'') " & _
"AND ((New_PO_Information.Cost_Center)<>'') " & _
"AND ((New_PO_Information.Description)<>'');"
Can someone tell me where I went wrong and correct the code, please?
It's probably this comma here: "Fiscal_Calendar.FWeek, " & _
There shouldn't be a comma before the FROM statement. And make sure you only have one FROM statement:
stSQL = "INSERT INTO PO_Information " & _
"(Partner, PO_Number, PO_Title, Cost_Center, Description, Line_1_Amt, Line_2_Amt, Date_Added, Month_Added, Year_Added, FY, Qtr, FY_Qtr, FW, FWeek)" & _
"Select New_PO_Information.Partner, " & _
"New_PO_Information.PO_Number, " & _
"New_PO_Information.PO_Title, " & _
"New_PO_Information.Cost_Center, " & _
"New_PO_Information.Description, " & _
"New_PO_Information.Line_1_Amt, " & _
"New_PO_Information.Line_2_Amt, " & _
"New_PO_Information.Date_Added, " & _
"New_PO_Information.Month_Added, " & _
"New_PO_Information.Year_Added, " & _
"Fiscal_Calendar.FY, " & _
"Fiscal_Calendar.Qtr, " & _
"Fiscal_Calendar.FY_Qtr, " & _
"Fiscal_Calendar.FW, " & _
"Fiscal_Calendar.FWeek " & _
"FROM New_PO_Information INNER JOIN Fiscal_Calendar " & _
"ON New_PO_Information.Date_Added = Fiscal_Calendar.Calendar"
stSQL = stSQL & _
" Where ((New_PO_Information.Partner)<>'') " & _
"AND ((New_PO_Information.PO_Number)<>'') " & _
"AND ((New_PO_Information.PO_Title)<>'') " & _
"AND ((New_PO_Information.Cost_Center)<>'') " & _
"AND ((New_PO_Information.Description)<>'');"
If I created an append query, here is the code. Just trying to convert this into my SQL statement that I posted earlier.
INSERT INTO PO_Information ( Partner, PO_Number, PO_TItle, Cost_Center, Description, Line_1_Amt, Line_2_Amt, Date_Added, Month_Added, Year_Added, FY, Qtr, FY_Qtr, FW, FWeek )
SELECT New_PO_Information.Partner, New_PO_Information.PO_Number, New_PO_Information.PO_TItle, New_PO_Information.Cost_Center, New_PO_Information.Description, New_PO_Information.Line_1_Amt, New_PO_Information.Line_2_Amt, New_PO_Information.Date_Added, New_PO_Information.Month_Added, New_PO_Information.Year_Added, Fiscal_Calendar.FY, Fiscal_Calendar.Qtr, Fiscal_Calendar.FY_Qtr, Fiscal_Calendar.FW, Fiscal_Calendar.FWeek
FROM New_PO_Information INNER JOIN Fiscal_Calendar ON New_PO_Information.Date_Added = Fiscal_Calendar.Calendar;

SQL where with Union and Left

Is it possible to add criteria in [ID] and not in [TypeID] in Left Join?
SQL = "SELECT " & _
"ADate As NewDate, " & _
"tblA.TypeID as ID, " & _
"tblAB.TypeControl as ControlID " & _
"FROM tblA " & _
"LEFT OUTER JOIN tblAB " & _
"ON tblAB.TypeID = tblA.TypeID " & _
"WHERE tblA.TypeID = " & Counter & " " & _ => Delete this one.
"UNION ALL SELECT " & _
"BDate As NewDate, " & _
"tblB.TypeID as ID, " & _
"tblAB.TypeControl as ControlID " & _
"FROM tblB " & _
"LEFT OUTER JOIN tblAB " & _
"ON tblAB.TypeID = tblB.TypeID " & _
"WHERE tblB.TypeID = " & Counter & " " & _ => Delete this one.
===
and place one WHERE on ID here
"WHERE ID = " & Counter & " " & _ => Like this one. But I am getting an error.
===
"ORDER BY NewDate;"
Delete the two WHERE from tblA and tblB.
Add one in ID in the end.
And create this one.
SQL = "SELECT " & _
"ADate As NewDate, " & _
"tblA.TypeID as ID, " & _
"tblAB.TypeControl as ControlID " & _
"FROM tblA " & _
"LEFT OUTER JOIN tblAB " & _
"ON tblAB.TypeID = tblA.TypeID " & _
"UNION ALL SELECT " & _
"BDate As NewDate, " & _
"tblB.TypeID as ID, " & _
"tblAB.TypeControl as ControlID " & _
"FROM tblB " & _
"LEFT OUTER JOIN tblAB " & _
"ON tblAB.TypeID = tblB.TypeID " & _
"WHERE tblB.TypeID = " & Counter & " " & _
"WHERE ID = " & Counter & " " & _
"ORDER BY NewDate;"
Thank you in advance.
You can check for ID's only once by wrapping your entire query in a subquery, and then check for IDs in the outer query, e.g.:
SELECT * FROM (
SELECT " & _
"ADate As NewDate, " & _
"tblA.TypeID as ID, " & _
"tblAB.TypeControl as ControlID " & _
"FROM tblA " & _
"LEFT OUTER JOIN tblAB " & _
"ON tblAB.TypeID = tblA.TypeID " & _
"UNION ALL SELECT " & _
"BDate As NewDate, " & _
"tblB.TypeID as ID, " & _
"tblAB.TypeControl as ControlID " & _
"FROM tblB " & _
"LEFT OUTER JOIN tblAB " & _
"ON tblAB.TypeID = tblB.TypeID "
) WHERE ID = " & Counter & "
However, depending on how the database engine optimizes this, it might take longer to execute. I recommend you don't do this, and leave your query as-is.
(Also, I leave the quotes mess to you, since your question shouldn't have these anyway).

Count SQL statement in Access VBA

I am trying to count records in an access table where certain criteria are met and insert the totals into another table in one record. I am doing so through vba and am trying to create a sql statement in there but for some reason it says I have too many line continuations when I try to add in anymore and I am really confused as to why. Any help would be greatly appreciated.
intYear = InputBox("What year is it currently?", "Year Input")
DoCmd.DeleteObject acTable, "ThisTable"
strCreate = "CREATE TABLE MarketSegmentTotals (" & vbCrLf & _
"[State Medicaid] TEXT," & vbCrLf & _
"Commercial TEXT," & vbCrLf & _
"HIX TEXT," & vbCrLf & _
"MMP TEXT," & vbCrLf & _
"[CMS Part D (CY " & intYear & ")] TEXT," & vbCrLf & _
"[CMS Part D (CY " & (intYear + 1) & ")] TEXT" & vbCrLf & _
");"
strCount = "INSERT INTO MarketSegmentTotals([State Medicaid], [Commercial], [HIX], [MMP], [CMS Part D (CY " & intYear & ")], [CMS Part D (CY " & (intYear + 1) & ")] ) " & _
"SELECT A.cnt, B.cnt, C.cnt, D.cnt, E.cnt " & _
"FROM ( " & _
"SELECT COUNT([FORMULARY ID]) as cnt " & _
"FROM ImportMetricsIDs " & _
"WHERE [Market Segment]= 'State Medicaid' " & _
") AS A " & _
", ( " & _
"SELECT COUNT([FORMULARY ID]) as cnt " & _
"FROM ImportMetricsIDs " & _
"WHERE [Market Segment]= 'Commercial' " & _
") as B " & _
", ( " & _
"SELECT COUNT([FORMULARY ID]) as cnt " & _
"FROM ImportMetricsIDs " & _
"WHERE [Market Segment]= 'HIX' " & _
") AS C " & _
", ( " & _
"SELECT COUNT([FORMULARY ID]) as cnt " & _
"FROM ImportMetricsIDs " & _
"WHERE [Market Segment]= 'MMP' " & _
") AS D "
VBA limits the number of lines joined by line continuation characters.
You can change this to redefine the variable to break the number of line continuation.
strCount = "blahblahblah" & _
"moreblahblahblah" & _
"lastblahforabit"
strCount = strCount & "evenmoreblah" & _
"toomuchblahblahblah"
Or eliminate the line continuation entirely.
strCount = "blahblahblah"
strCount = strCount & "moreblahblahblah"
strCount = strCount & "lastblahforabit"
strCount = strCount & "evenmoreblah"
strCount = strCount & "toomuchblahblahblah"

SQL Query works in MS-Access but cannot implement it in vb.net form

The block of code immediately following (given to me by a stackoverflow solver) works perfectly in MS-Access. I'm trying to convert it to work in a vb.net form accessing the very same MS-Access database. I get an error and cannot see my mistake. Are there any vb.net coders that can see what I'm doing wrong. The first block of code works in MS-Access and is the code I'm trying to convert. And the second block of code is my conversion attempt.
SELECT at.animalID, amt.milestoneType
FROM
animals_Table at
LEFT JOIN
(
SELECT animalID, milestoneType
FROM animalMilestones_Table
WHERE milestoneType = 'Intake'
) amt
ON at.animalID = amt.animalID
Now, my conversion attempt:
dim selectAnimal as string
selectAnimal = "SELECT at.animalID, amt.milestoneType" & _
" FROM animals_Table at" & _
" LEFT JOIN" & _
" (" & _
" SELECT animalID, milestoneType" & _
" FROM animalMilestones_Table" & _
" WHERE milestoneType = '" & "Intake" & "'" & _
" ) amt" & _
" ON at.animalID = amt.animalID"
The error code I get is
!ErrorInfo.GetDescription failed with E_FAIL(0x80004005)
It appears that ACE.OLEDB doesn't like at as a table alias. Try this instead
Dim selectAnimal As String
selectAnimal = "SELECT atbl.animalID, amtbl.milestoneType" & _
" FROM animals_Table atbl" & _
" LEFT JOIN" & _
" (" & _
" SELECT animalID, milestoneType" & _
" FROM animalMilestones_Table" & _
" WHERE milestoneType = '" & "Intake" & "'" & _
" ) AS amtbl" & _
" ON atbl.animalID = amtbl.animalID"

Query - Error assigning value to variable in VB

I have the following code to query in VB6:
SQL = " if object_id('tempdb..#MovSeq','U') is not null drop table #MovSeq;" & _
" declare #Data_Inicio datetime, #Data_Fim datetime; set dateformat dmy; set #Data_Inicio = DataInicio; set #Data_Fim = DataFinal; set #Data_Fim = DateAdd(day, +1, #Data_Fim); " & _
" with Mov as ( SELECT EI.Cod_Empresa, EI.Cod_Estoque, EI.Cod_Produto, 'E' as Tipo_Mov, E.Dta_Entrada as Data_Mov, EI.id_Doc as NF, EI.Qtde, EI.V_Unitario, EI.V_Total " & _
" from Entrada_Itens as EI inner join Entrada as E on EI.Cod_Empresa=E.Cod_Empresa and EI.id_Doc=E.id_Doc " & _
" where E.Dta_Entrada >= #Data_Inicio and EI.Cod_Empresa='" & Sys.Empresa & "' and EI.Cod_Estoque='" & dcEstoque.BoundText & "' and EI.Cod_Produto='" & dtProdutos.BoundText & "' " & _
" Union " & _
" SELECT SI.Cod_Empresa, SI.Cod_Estoque, SI.Cod_Produto, 'S', S.Dta_Entrada , SI.id_Doc, -SI.Qtde, SI.V_Unitario, SI.V_Total " & _
" from Saida_Itens as SI inner join Saida as S on SI.Cod_Empresa=S.Cod_Empresa and SI.id_Doc=S.id_Doc " & _
" where S.Dta_Entrada >= #Data_Inicio and SI.Cod_Empresa='" & Sys.Empresa & "' and SI.Cod_Estoque='" & dcEstoque.BoundText & "' and SI.Cod_Produto='" & dtProdutos.BoundText & "' " & _
" Union " & _
" SELECT Cod_Empresa, Cod_Estoque, Cod_Produto, 'A', #Data_Inicio, null, null, null, null " & _
" From Estoque " & _
" where Cod_Empresa='" & Sys.Empresa & "' and Cod_Estoque='" & dcEstoque.BoundText & "' and Cod_Produto='" & dtProdutos.BoundText & "') " & _
" SELECT *, Seq= row_number() over (partition by Cod_Empresa, Cod_Estoque, Cod_Produto order by Data_Mov desc, Tipo_Mov desc) into #MovSeq from Mov; " & _
" create unique clustered index IndMovSeq on #MovSeq (Cod_Empresa, Cod_Estoque, Cod_Produto, Seq); " & _
" SELECT M.Cod_Empresa, M.Cod_Estoque, M.Cod_Produto, P.Descricao," & _
" Estoque= case when M.Seq=1 then E.Qtde_Estoque else (E.Qtde_Estoque - (SELECT sum(Mi.Qtde) from #MovSeq as Mi " & _
" Where Mi.Cod_Empresa = M.Cod_Empresa And Mi.Cod_Estoque = M.Cod_Estoque And Mi.Cod_Produto = M.Cod_Produto and Mi.Seq < M.Seq)) end " & _
" from #MovSeq as M inner join " & _
" Estoque as E on M.Cod_Empresa=E.Cod_Empresa and M.Cod_Estoque=E.Cod_Estoque and M.Cod_Produto=E.Cod_Produto inner join " & _
" Produtos as P on M.Cod_Empresa=P.Cod_Empresa and M.Cod_Estoque=P.Cod_Estoque and M.Cod_Produto=P.Cod_Produto " & _
" where Data_Mov < #Data_Fim " & _
" order by M.Cod_Empresa, M.Cod_Estoque, M.Cod_Produto, Seq desc; " & _
" drop table #MovSeq;"
the error appears 'invalid columm name' when run showing DataInicio as a reason
I know the error is in the assignment of the variable. but how to solve.
Thanks for the help...
Your type of code is very prone to SQL Injection attacks...
Are you escaping the variable values correctly? A simple quote (') in one of the variables can change the SQL string completely...
You should consider using parameters to pass values instead of building SQL commands using string concatenation.