SQL Sum statement very slow - sql

new to SQL and having trouble with this code. It seems that the "SUM" function is just really slow. It times out if the date range is more than 5 days. I have to loop thru this 115 times and cover a date range of 180 days. Any ideas on what I can do to speed it up? The string times out in the SQL Enterprise Manager as well.
I've heard mention of using a "pivot" command, but don't know if that is the answer or how to implement it. TIA
strSQLRead = "SELECT SUM(BatchRecordDetail.BRD_Actual) AS LbsBatched, BatchRun.BAT_CoatingLBS AS CoatingLbs, " _
& "BatchRun.BAT_ID AS RunID " _
& "FROM BatchRun " _
& "INNER JOIN BatchRecordMaster ON BatchRun.BAT_HmiRunID = BatchRecordMaster.BRM_BatchRunID " _
& "AND BatchRun.BAT_Area = BatchRecordMaster.BRM_Area " _
& "INNER JOIN BatchRecordDetail ON BatchRecordMaster.BRM_Area = BatchRecordDetail.BRD_Area " _
& "AND BatchRecordMaster.BRM_HmiBatchID = BatchRecordDetail.BRD_BatchRecordID " _
& "WHERE (BatchRun.BAT_ExtruderEnd BETWEEN CONVERT(DATETIME, '" & Format(ToDate, "yyyy-MM-dd") & " 00:00:00', 102) " _
& "AND CONVERT(DATETIME, '" & Format(FromDate, "yyyy-MM-dd") & " 00:00:00', 102)) AND (BatchRun.BAT_RunComplete = 1) " _
& "AND BatchRun.BAT_FormulaCode = '" & sFormula(i) & "'" _
& "GROUP BY BatchRun.BAT_FormulaCode,BatchRun.BAT_ID, BatchRun.BAT_CoatingLBS " _
& "HAVING (BatchRun.BAT_CoatingLBS Is Not Null)"
Here is the string as trapped in code. Just wondering if anyone had any ideas. thx
SELECT Sum(batchrecorddetail.brd_actual) AS LbsBatched,
batchrun.bat_coatinglbs AS CoatingLbs,
batchrun.bat_id AS RunID
FROM batchrun
INNER JOIN batchrecordmaster
ON batchrun.bat_hmirunid = batchrecordmaster.brm_batchrunid
AND batchrun.bat_area = batchrecordmaster.brm_area
INNER JOIN batchrecorddetail
ON batchrecordmaster.brm_area = batchrecorddetail.brd_area
AND batchrecordmaster.brm_hmibatchid =
batchrecorddetail.brd_batchrecordid
WHERE ( batchrun.bat_extruderend BETWEEN
CONVERT(DATETIME, '2014-06-26 00:00:00', 102)
AND
CONVERT(DATETIME, '2014-06-26 00:00:00'
, 102) )
AND ( batchrun.bat_runcomplete = 1 )
AND batchrun.bat_formulacode = '3100007'
GROUP BY batchrun.bat_formulacode,
batchrun.bat_id,
batchrun.bat_coatinglbs
HAVING ( batchrun.bat_coatinglbs IS NOT NULL )
I can't post pics cause I don't have enough reputation points.
How would I display what else is needed to help answer the question?

Related

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")

Syntax error in Microsoft Access SQL Select query in VBA procedure

I am having following VBA Code that has been giving a syntax error. Can someone please help me figure out what is causing the error?
Private Sub Command11_Click()
Dim EndingDate As Date
'Getting ending date from Label named endDate
EndingDate = endDate
StartingDateTxt = DateSerial(Year(EndingDate), Month(EndingDate) - 15, Day(EndingDate))
Dim customerRecords As New ADODB.Recordset
customerRecords.Open "SELECT COUNT(*) AS N FROM (SELECT DISTINCT E.Date,"&_
"E.[Inv Num], E.CusName, E.[Name Street1], E.[Name Street2], "&_
"E.[Name City], E.[Name State], E.[Name Zip], E.[Account #], E.Amount FROM TempFromExcel "&_
"AS E INNER JOIN TempFromExcel AS X ON E.CusName = X.CusName "&_
"WHERE (((DateDiff("d",X.Date,E.Date))>=30)) AND E.Date >= '" & StartingDateTxt & "' and"&_
"E.Date <= '" & endDate & "') AS T ;", _
CodeProject.Connection , _
adOpenStatic, _
adLockOptimistic, _
adCmdText
MsgBox customerRecords("N")
End Sub
My Query is taking both dates and finding the results that are between the two dates.
I think I may be missing at that part only. The rest seems fine as I had explicitly check the query and it runs fine. So is this right ?
E.Date >= '" & StartingDateTxt & "' and E.Date <= '" & endDate & "'
This has been corrected, in the answer but still am getting syntax error in Select statement first line. Am missing something?
In Microsoft Access SQL query you have to encapsulate Date value into ##, like for example, #06/01/2015#. Pertinent to your case it should look like:
E.Date >= #" & StartingDateTxt & "# AND E.Date <=#" & endDate & "#"
Hope this may help.
Try changing these lines:
"WHERE (DateDiff('d', X.Date, E.Date) >= 30 AND E.Date >= #" & Format(StartingDateTxt, "yyyy\/mm\/dd") & "# and " & _
"E.Date <= #" & Format(endDate, "yyyy\/mm\/dd") & "#) AS T ;", _

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.

How do I delete files from a table in MSDE 2000 that is selected by 3 joins?

I have a VB6 program that uses a n Access backend. The query that I am currently using is
sQuery = "DELETE tblResultNotes.* " & _
"FROM (tblJobs INNER JOIN tblResults ON tblJobs.JobID=tblResults.JobID) INNER JOIN tblResultNotes ON tblResults.ResultID=tblResultNotes.ResultID " & _
"WHERE (tblJobs.CreateDate)< #" & strDate & "# " & _
"AND tblResults.StartTime < #" & strDate & "#;"
I have changed my backend to MSDE 2000 and now this query is giving me a syntax error near '*'. Could someone help me out?
Thanks,
Tom
Try changing your SQL to this:
sQuery = "DELETE FROM tblREsultNotes " & _
"FROM " & _
" tblJobs" & _
" INNER JOIN tblResults ON tblJobs.JobID=tblResults.JobID" & _
" INNER JOIN tblResultNotes ON tblResults.ResultID=tblResultNotes.ResultID" & _
"WHERE tblJobs.CreateDate < '" & strDate & "'" & _
"AND tblResults.StartTime < '" & strDate & "'"
Note the date delimiter change to ' instead of #.