SQL Access Iif(aantal_instroom) as instroom - sql

I've got this:
sql = "SELECT " & _
"proces_id, " & _
"proces_naam, " & _
"voorraad, " & _
"voorraad_te_laat, " & _
"voorraad_verificatie, " & _
"voorraad_verificatie_te_laat, " & _
"teamplanning, " & _
"teamplanning_verificatie, " & _
"Iif(IsNull(teamplanning_totaal), 0, teamplanning_totaal) + Iif(IsNull(teamplanning), 0, teamplanning) AS totaal_teamplanning, " & _
"Iif(IsNull(teamplanning_totaal_verificatie), 0, teamplanning_totaal_verificatie) + Iif(IsNull(teamplanning), 0, teamplanning_verificatie) AS totaal_teamplanning_verificatie, " & _
"Round(Iif(IsNull(teamplanning), 0, (teamplanning * proces_normtijd * Iif(IsNull(productiviteit_factor), 1, productiviteit_factor)) / 60), 2) AS teamplanning_uren, " & _
"Round(Iif(IsNull(teamplanning_verificatie), 0, (teamplanning_verificatie * proces_normtijd_verificatie * Iif(IsNull(productiviteit_factor), 1, productiviteit_factor)) / 60), 2) AS teamplanning_uren_verificatie, "
If IsNull(Datum) Then
sql = sql & "null AS verschil, " & _
"null AS verschil_verificatie, "
Else
sql = sql & "Iif(IsNull(voorraad), 0, voorraad) - Iif(IsNull(teamplanning), 0, teamplanning) - Iif(IsNull(teamplanning_totaal), 0, teamplanning_totaal) AS verschil, " & _
"Iif(IsNull(voorraad_verificatie), 0, voorraad_verificatie) - Iif(IsNull(teamplanning_verificatie), 0, teamplanning_verificatie) - Iif(IsNull(teamplanning_totaal_verificatie), 0, teamplanning_totaal_verificatie) AS verschil_verificatie, "
End If
sql = sql & "proces_normtijd, " & _
"proces_normtijd_verificatie, " & _
"Iif(IsNull(realisatie_cases), 0, realisatie_cases) AS realisatie_cases_aantal, " & _
"Iif(IsNull(realisatie_cases_verificatie), 0, realisatie_cases_verificatie) AS realisatie_cases_aantal_verificatie, " & _
"Iif(IsNull(ingeplande_cases), 0, ingeplande_cases) AS ingeplande_cases_aantal, " & _
"Iif(IsNull(ingeplande_cases_verificatie), 0, ingeplande_cases_verificatie) AS ingeplande_cases_aantal_verificatie, " & _
"volgorde, "
sql = sql & "Iif(IsNull(voorraad_gisteren), 0, voorraad_gisteren) AS instroom, " & _
"Iif(IsNull(voorraad_verificatie_gisteren), 0, voorraad_verificatie_gisteren) AS instroom_verificatie "
sql = sql & "FROM tmp_planning_proces " & _
"WHERE userid = '" & EscapeString(LCase(mod_global.RealUser)) & "' " & _
"AND team_id = " & TeamID & " " & _
IIf(IsNull(MedewerkerGroepID), "AND medewerker_groep_id is null ", "AND medewerker_groep_id = " & MedewerkerGroepID & " ") & _
IIf(IsNull(Datum), "AND week = " & week & " AND jaar = " & jaar & " ", "AND datum = #" & Format(Datum, "yyyy-mm-dd") & "# ") & _
"ORDER BY volgorde ASC "
What I need to change is:
"Iif(IsNull(voorraad_gisteren), 0, voorraad_gisteren) AS instroom".
It needs to be:
"Iif(IsNull(aantal_instroom), 0, aantal_instroom) AS instroom".
The problem is that it comes from another table called instroom. The query I didn't make myself and I have limited query skills so I tried this:
"Iif(IsNull(Select aantal_instroom From instroom), 0, aantal_instroom) AS instroom"
but that doesn't work, suddenly no data appears anymore.
Does anybody know how to do this?

First of all there is a much better way to do:
IIf(IsNull(voorraad_gisteren), 0, voorraad_gisteren)
It is:
Nz(voorraad_gisteren, 0)
Now to your question. First you have to make sure the table instroom is part of your FROM section of the SQL statement. Example:
FROM tmp_planning_proces INNER JOIN instroom ON ... [whatever fields link the two tables together]
Then you can refer to any field on the table like this:
instroom.aantal_instroom
IIf(IsNull(instroom.aantal_instroom), 0, instroom.aantal_instroom) AS instroom
or even better:
Nz(instroom.aantal_instroom,0) AS instroom
I also agree with the comment that using the same field alias as the table name is probably a bad idea and bound to cause confusion in the future.

Related

Having issues with how to use ' or " in sql statement and query using concatrelated function

I have the following code using the ConcatRelated function. the current sql works with 1 where condition but I can't figure out how to get the sql to work with 2 conditions. It works when use it in a query. I get issues and the code does not debug.
ItemsShpdInvSQL = "SELECT InvoiceAllShippedItems.ShipmentID, InvoiceAllShippedItems.ShipType, " _
& "InvoiceAllShippedItems.BillTo, InvoiceAllShippedItems.CustID AS Consignee, " _
& "InvoiceAllShippedItems.PayMethod, InvoiceAllShippedItems.PaidInFull, " _
& "First(InvoiceAllShippedItems.Units) AS Units, " _
& "'Freight Charges - Ref. WR: ' & (ConcatRelated('[WR]'," _
& "'[InvoiceAllShippedItems]','[BillTo] =' & [BillTo])) & " _
& "' - (' & Sum([Chargeable]) & ' ' & [Units] & ' " _
& ") - Number of Pieces: ' & [NoPieces] AS InvDetails, " _
& "Sum(InvoiceAllShippedItems.[# of Pieces]) AS NoPieces, " _
& "Sum(InvoiceAllShippedItems.Chargeable) AS Charge, " _
& "CustRate([custid],[ShipType]) AS CustomerRate, " _
& "IIf(([Charge])<6.1,20/[Charge],[CustomerRate]) AS RateMin " _
& "FROM InvoiceAllShippedItems " _
& "GROUP BY InvoiceAllShippedItems.ShipmentID, " _
& "InvoiceAllShippedItems.ShipType, InvoiceAllShippedItems.BillTo, " _
& "InvoiceAllShippedItems.CustID, InvoiceAllShippedItems.PayMethod, " _
& "InvoiceAllShippedItems.PaidInFull, InvoiceAllShippedItems.Units, " _
& "CustRate([custid],[ShipType]) " _
& "ORDER BY InvoiceAllShippedItems.BillTo;"
'& "CustRate([custid],[ShipType]);"
with this it works in a query but not in the code above:
'concatrelated("[WR]","InvoiceAllShippedItems","[BillTo]&[PayMethod] ='" & [BillTo] & [PayMethod] & "'")

Cannot interpret a BASIC file querying SQL

So, I am trying to figure out where the TOTAL_CHG is coming from. Below is a snippet of where it is first used (not defined at all before).
...
sStrBalance = " (TOTAL_CHG - (ISNULL((SELECT SUM(isnull(t.amount, 0)) FROM transactions t " & _
" WHERE cp.contpolid = t.contpolid AND t.tran_date <= '" & GRepdate & "'), 0) + " & _
" ISNULL((SELECT SUM(isnull(dirpayamt, 0)) FROM bkrtrans bkr " & _
" WHERE cp.contpolid = bkr.contpolid), 0))) "
...
And then the next block of code that references it again is as follows:
...
strSQL = strSQL & vbCrLf & " SELECT cp.Contpolid, cp.CTYPE_ID, cp.C#, cp.REV, " & _
vbCrLf & "CASE WHEN cp.Div_Code = 'GM' THEN 'SLP' ELSE 'SCA' END, " & _
vbCrLf & "cp.Effective_ as EFFDATE, ADJUSTMENT, cp.terminatio, cp.TOTAL_CHG, " & _
vbCrLf & " ISNULL((SELECT SUM(isnull(t.amount, 0)) FROM transactions t " & _
vbCrLf & " WHERE cp.contpolid = t.contpolid AND t.tran_date <= '" & GRepdate & "'), 0) AS Payments, " & _
vbCrLf & " ISNULL((SELECT SUM(isnull(dirpayamt, 0)) FROM bkrtrans bkr " & _
vbCrLf & " WHERE cp.contpolid = bkr.contpolid), 0) AS BrkPayment, " & _
sStrBalance & " AS Balance, cast(0 as numeric(12,2)) as SixtyDays, cast(0 as numeric(12,2)) as NinetyDays , " & _
vbCrLf & " cast(0 as numeric(12,2)) as OverNinetyDays , CASE WHEN Register_D IS NULL THEN 'N' ELSE CASE WHEN Register_D < '" & GRepdate & "' THEN 'Y' ELSE 'N' END END "
strSQL = strSQL & vbCrLf & " FROM CONTRACTS_POLICIES cp (NOLOCK) /*JOIN Salesmen s (NOLOCK) ON s.salesmenid = cp.sales1*/ " & _
vbCrLf & " Where cp.CTYPE_ID = 1 And cp.Cancel_dat Is Null and CP.Sales1 is Not NULL " & _
vbCrLf & " AND ((CP.Effective_ <= '" & GRepdate & "' AND CP.Rev = 0) OR (CP.Adjustment <= '" & GRepdate & "' AND CP.Rev > 0)) " & _
vbCrLf & " AND NOT((" & sStrBalance & " > 0 AND cp.Effective_ <= '01/01/1996') OR (" & sStrBalance & "< 0 AND cp.Effective_ <= '01/01/1998')) " & _
vbCrLf & " And " & sStrBalance & " <> 0 "
...
What table is it even coming from? It seems like it is defined in the first block of code but isn't really a value yet.

Why does my Access SQL VBA code jump out of the Sub?

My code is exiting out of the sub on the line that says "CurrentDb.Execute strSQL_Insert_Data". Do you know why this is happening?
Local_Array = Array("dbo_Tape_Capture_Local_tbl", "dbo_Tape_Local_tbl", "dbo_Tape_Memo_Local_tbl")
Server_Array = Array("dbo_Tape_Capture", "dbo_Tape", "dbo_Tape_Memo")
For i = 0 To UBound(Local_Array)
strSQL_Insert_Data = "INSERT INTO [" & Local_Array(i) & "] " & _
"SELECT [" & Server_Array(i) & "].* " & _
"WHERE (LEFT([" & Server_Array(i) & "].header__situs_loan_id," & _
Len([Forms]![Login Page]![CBO_Job_Select_Login]) & ") = " & _
"[Forms]![Login Page]![CBO_Job_Select_Login]);"
CurrentDb.Execute strSQL_Insert_Data
CurrentDb.Close
Next i
--Added Printed out code--
INSERT INTO [dbo_Tape_Capture_Local_tbl] SELECT [dbo_Tape_Capture].*
WHERE (LEFT([dbo_Tape_Capture].header__situs_loan_id,14) = [Forms]![Login Page]![CBO_Job_Select_Login]);
There is missing FROM TableName in your query. Replace TableName with Actual Table Name
strSQL_Insert_Data = "INSERT INTO [" & Local_Array(i) & "] " & _
"SELECT [" & Server_Array(i) & "].* " & _
"FROM [" & Server_Array(i) & "] " & _
"WHERE (LEFT([" & Server_Array(i) & "].header__situs_loan_id," & _
Len([Forms]![Login Page]![CBO_Job_Select_Login]) & ") = " & _
"[Forms]![Login Page]![CBO_Job_Select_Login]);"

Access 2010 VBA SQL INSERT with multiple SELECT

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

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.