VB 2005 syntax error - sql

can someone help me check for the below coding, I have a syntax error.
I may have missed out some syntax.
"WHERE PaymentLedger.JobScheduleGUID = JobSchedule.GUID " & _
"AND JobSchedule.CLID = LabourProfile.CLID " & _
"AND LabourProfile.CLNationality = 'MALAYSIA' " & _
"AND (PaymentLedger.SOCSOEmployerContri > 0 or PaymentLedger.EPFEmployeeContri > 0) " & _
'"AND (PaymentLedger.Credit > 0) " & _
"AND (PaymentLedger.Credit > 0 or PaymentLedger.Debit > 0) " & _
Thanks

Look at these two lines:
'"AND (PaymentLedger.Credit > 0) " & _
"AND (PaymentLedger.Credit > 0 or PaymentLedger.Debit > 0) " & _
1 - remove the ' on the first one
2 - Remove the & _ on the second one

Related

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.

SQL Access Iif(aantal_instroom) as instroom

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.

SQL ExecuteQuery 3061 error message

I've got this:
sql = "INSERT INTO instroom ( " & _
"team_id, " & _
"proces_id, " & _
"datum, " & _
"aantal_instroom, " & _
"ctime, " & _
"cuser, " & _
"mtime, " & _
"muser " & _
") "
sql = sql & "SELECT " & _
"team_id, " & _
"proces_id, " & _
"datum, " & _
"SUM(aantal_instroom), " & _
"#" & Format(MTime, "yyyy-mm-dd hh:mm:ss") & "#, " & _
"" & mod_global.RealUserID & ", " & _
"#" & Format(MTime, "yyyy-mm-dd hh:mm:ss") & "#, " & _
"" & mod_global.RealUserID & " " & _
"FROM tmp_import_instroom " & _
"WHERE userid = '" & EscapeString(LCase(mod_global.RealUser)) & "' " & _
"AND team_id <> 0 " & _
"AND proces_id <> 0 "
sql = sql & "GROUP BY team_id, proces_id, datum " & _
"HAVING SUM(aantal_cases) > 0 "
When it goes through:
-- Execute Query
Private Function executeSQL(ByVal sql As String, Optional ByVal autoCommit As Boolean = False) As Boolean
On Error GoTo executeSQLError
executeSQL = False
If mod_global.DevStart Then QueryNum = QueryNum + 1
If mod_global.DevStart Then Call saveQueryToFile(sql)
' Check if database is open
If Not testConn Then
Call openDB
End If
If startTrans Then
db.Execute sql
executeSQL = True
If autoCommit Then
executeSQL = commitDB
End If
End If
DoEvents
Exit Function
executeSQLError:
Debug.Print ("executeSQL - " & Err.Number & " : " & Err.Description)
Call writeToLog("executeSQL - " & Err.Number & " : " & Err.Description)
End Function
I get the error message
"Runtime Error 3061: Too few parameters. Expected 1.".
What am I missing? I did debug.print and still can't find something wrong.
Here are my column names from tmp_import_instroom:
results of debug.print
insert into instroom (
team_id
, proces_id
, datum
, aantal_instroom
, ctime
, cuser
, mtime
, muser
)
select
team_id
, proces_id
, datum
, SUM(aantal_instroom)
, #2017-02-23 20:22:33#
, 310
, #2017-02-23 20:22:33#
, 310
from tmp_import_instroom
where userid = 'xg30222'
and team_id <> 0
and proces_id <> 0
group by team_id
, proces_id
, datum
having SUM(aantal_cases) > 0
Unless it's not showing, there's no ctime, cuser, mtime or muser in your table. Therefore, you need to alias your calculated fields.
sql = sql & "SELECT " & _
"team_id, " & _
"proces_id, " & _
"datum, " & _
"SUM(aantal_instroom) as aantal_instroom, " & _
"#" & Format(MTime, "yyyy-mm-dd hh:mm:ss") & "# as ctime, " & _
"" & mod_global.RealUserID & " as cuser, " & _
"#" & Format(MTime, "yyyy-mm-dd hh:mm:ss") & "# as mtime, " & _
"" & mod_global.RealUserID & " as muser " & _
"FROM tmp_import_instroom " & _
"WHERE userid = '" & EscapeString(LCase(mod_global.RealUser)) & "' " & _
"AND team_id <> 0 " & _
"AND proces_id <> 0 "

SQL query assistance needed with 'NOT'

I'm working out of VB6 with SQL SERVER 2012. I found myself in a pickle. Basically i have a query that works fine and pulls the necessary data in SQL SERVER, however, I'm having a difficult time translating it to vb6 SQL code. Here's a working query in SQL SERVER...
SELECT 'TotalSum' = SUM(Units)
FROM tblDetail
WHERE MemberID = '117'
AND CAST(SStartD AS DATETIME) >= '4/1/2016'
AND CAST(SStartD AS DATETIME) <= '4/7/2016'
AND Service = 166
AND [CODE] IN('1919')
AND NOT(InvoiceNo = '11880'
AND DtlNo = 2
)
AND NOT(InvoiceNo = '11880'
AND AdjNo = 2
);
So when I try to write it in my vb6 application i do something like
SELECT 'TotalSum' = SUM(Units)
FROM tblDetail
WHERE MemberID = '117'
AND CAST(SStartD AS DATETIME) >= '4/1/2016'
AND CAST(SStartD AS DATETIME) <= '4/7/2016'
AND Service = 166
AND [CODE] IN('1919')
AND (InvoiceNo <> '11880'
AND DtlNo <> 2
)
AND (InvoiceNo <> '11880'
AND AdjNo <> 2
);
However, this is not giving me the same results. Whats happening is in my last two clauses
( InvoiceNo <> '11880' AND DtlNo<> 2) AND (InvoiceNo <> '11880' AND AdjNo <> 2)
When I run them finally in SQL SERVER don't have paranthesis and its absolutely detrimental that the 2 seperate clauses are in paranthesis. Anyone know what I can do? I think my last resort might be to create a store procedure but i don't really want to do that.
EDIT:
g_SQL = "SELECT 'SUM' = SUM(Units) " & _
"FROM tblDetail WHERE " & _
"MemID = " & udtCDtl.Lines(udtCDtlIdx).MemID & " AND " & _
"CAST(SStartD As DateTime) >= '" & StartDate & "' AND " & _
"CAST(SStartD As DateTime) <= '" & DateAdd("d", -1, EndDate) & "' AND " & _
"Service = 166 AND " & _
"[CODE] IN (‘1919’)) And " & _
("InvoiceNo <> " & InvoiceDtlRS!InvoiceHdrNo & " OR " & _
"DtlNo <> " & (InvoiceDtlRS! InvoiceDtlNo, "")) & " AND " & _
("InvoiceNo <> " & InvoiceDtlRS!InvoiceHdrNo & " OR " & _
"AdjNo <> " & InvoiceDtlRS! InvoiceDtlNo)
Your translation of NOT(InvoiceNo = '11880' AND DtlNo = 2) to (InvoiceNo <> '11880' AND DtlNo <> 2) is incorrect.
In formal logic, !(A & B) is equivalent to (!A or !B), so it should be:
(InvoiceNo <> '11880' OR DtlNo <> 2)
This is why you're getting different results. However, why not use the original query? There's nothing in VB6 which would prevent it.
EDIT
g_SQL = "SELECT 'SUM' = SUM(Units) " & _
"FROM tblDetail WHERE " & _
"MemID = " & udtCDtl.Lines(udtCDtlIdx).MemID & " AND " & _
"CAST(SStartD As DateTime) >= '" & StartDate & "' AND " & _
"CAST(SStartD As DateTime) <= '" & DateAdd("d", -1, EndDate) & "' AND " & _
"Service = 166 AND " & _
"[CODE] IN (‘1919’)) And " & _
("InvoiceNo <> " & InvoiceDtlRS!InvoiceHdrNo & " OR " & _
"DtlNo <> " & (InvoiceDtlRS! InvoiceDtlNo, "")) & " AND " & _
("InvoiceNo <> " & InvoiceDtlRS!InvoiceHdrNo & " OR " & _
"AdjNo <> " & InvoiceDtlRS! InvoiceDtlNo)
You've got a ) in the wrong place twice. Also, the ) on the final live would be a syntax error I think. The last 5 lines should be:
"[CODE] IN (‘1919’) And " & _
("InvoiceNo <> " & InvoiceDtlRS!InvoiceHdrNo & " OR " & _
"DtlNo <> " & (InvoiceDtlRS!InvoiceDtlNo, "") & " AND " & _
("InvoiceNo <> " & InvoiceDtlRS!InvoiceHdrNo & " OR " & _
"AdjNo <> " & InvoiceDtlRS!InvoiceDtlNo & ")"
This should work. I'm able to use SQL queries using NOT with ADODB in VB6.
g_SQL = "SELECT 'SUM' = SUM(Units) " & _
"FROM tblDetail WHERE " & _
"MemID = " & udtCDtl.Lines(udtCDtlIdx).MemID & " AND " & _
"CAST(SStartD As DateTime) >= '" & StartDate & "' AND " & _
"CAST(SStartD As DateTime) <= '" & DateAdd("d", -1, EndDate) & "' AND " & _
"Service = 166 AND " & _
"[CODE] IN ('1919')) And " & _
"NOT (InvoiceNo = " & InvoiceDtlRS!InvoiceHdrNo & " AND DtlNo = " & InvoiceDtlRS!InvoiceDtlNo & ") AND " & _
"NOT (InvoiceNo = " & InvoiceDtlRS!InvoiceHdrNo & " AND AdjNo = " & InvoiceDtlRS!InvoiceDtlNo & ")"
While Marc may have given you a query that works, Simon's question is still valid. The only reason your original query wouldn't work is because you munged the quotes. You'll notice that your parentheses by the reference to InvoiceNo are outside the quotes rather than inside them (there are other problems as well, from changing your original query, but I'll leave you to figure those out for yourself). That makes them not part of the quoted string, and instead part of the VB6 expression. Frankly, Marc isn't doing you any favors by providing an alternative SQL query that happens to have all the VB6 syntax correct, while yours does not. The real problem is that you haven't worked out how to put a SQL query into a quoted string carefully enough.
You can't afford that kind of carelessness if you want to be good at what you're doing. I don't say this to be offensive, but to get your attention. By adopting Marc's solution as the correct one, you haven't really solved your problem, because your problem is a mindset that doesn't think about anything except getting something to work. That mindset makes for the worst kind of programmer, the kind that writes terrible code (hundreds of lines of code where it could be done in 10, for example) that makes nightmares for people who have to maintain it later. Don't be one of those people. When you don't know why something isn't working, go to the trouble of figuring out why. You only have to do it once for each problem, and that mindset will stand you well as you continue to develop your skills.
Again, no disrespect intended. I'm just trying to get you to understand how to avoid getting in "pickles" like this one in future. Hopefully, the next time you post a question here, the "pickle" you're in will be more sophisticated. :)
EDIT: I guess I'm not making myself clear enough. The simple rule is that you need to enclose everything in the working SQL query in quoted strings, and replace the literal search values with references to text boxes, fields, or whatever. So:
sql = "SELECT 'TotalSum' = SUM(Units) " & _
"FROM tblDetail " & _
"WHERE MemberID = '" & myVariable & "' " & _
"AND CAST(SStartD AS DATETIME) >= '" & myVariable & "' " & _
"AND CAST(SStartD AS DATETIME) <= '" & myVariable & "' " & _
"AND Service = 166 " & _
"AND [CODE] IN('1919') " & _
"AND NOT(InvoiceNo = '" & myVariable & "' " & _
"AND DtlNo = " & myVariable & _
")" & _
"AND NOT(InvoiceNo = '" & myVariable & "' " & _
"AND AdjNo = " & myVariable & _
");"
Where myVariable is whatever variable reference you want to replace your literal string with. Any examples you've given have errors in placement of double quotes, which is why you aren't getting the result you want, which is presumably a replication of your working SQL query. The reason Marc's works is not because he altered your original query (it doesn't look like he has, except to put it on less lines) but because he placed his quotation marks correctly. The reason your and simon's solutions don't work is because neither of you have. Going back to your original post, the reason that the parentheses fail to show is because you haven't enclosed them in quotes. Marc has.

Trying to process SQL query within Excel VBA; incorrect syntax near 'a'

I'm a novice programmer at work and I'm struggling with a little snippet of code I need. I've read through various posts but I did not find anything that helped at last.
What I'm trying to do is to launch my SQL-Query within my vba macro but i keep getting "incorrect syntax near 'a'" error and i couldn't figure out why.
Set con = New ADODB.Connection
Set rs = CreateObject("ADODB.Recordset")
con.Open sConStr
Set rs = con.Execute("SELECT CONVERT(char(10), a.[Starttime], 104) as Date " & _
",CONVERT(char(8),a.[Starttime], 114) AS Starttime " & _
",CONVERT(char(8),a.[Endtime], 114) AS Endtime " & _
",DATEDIFF(s,a.[Starttime], a.[Endtime]) AS Duration " & _
",a.[BCMLogin] " & _
",a.[Type] " & _
",a.[PRSProfil] " & _
",b.[Location] " & _
"FROM [xxxxxxx].[dbo].[Report] AS a LEFT JOIN [xxxxxxx].[dbo].[Stammdaten] AS b on a.[Loginname] = b.[Username] " & _
"where " & _
"cast(a.[Starttime] as date) between #" & str_DFrom & "# AND #" & str_DUntil & "#" & _
"AND " & _
"a.[PRSProfil] != ''" & _
"AND " & _
"a.[Type] != 'StatusWorking'" & _
"Order BY " & _
"1,2")