Query Syntax & Use Of Variables
Dec 5, 2004
All,
I've become aware that if I create a variable in the select statement like this in Access:
SELECT Table1.ID, Sum([A]+[B]+[C]) AS TotSum
That I cannot reliably use said variable later in the same statement:
SELECT Table1.ID, Sum([A]+[B]+[C]) AS TotSum
FROM Table1
GROUP BY Table1.ID
ORDER BY TotSum DESC;
It will ask me to "enter a parameter value" for TotSum. When I do, in this example, it still sorts in correctly, but in a larger more detailed query it gets a little confused. I instead have to re-use the equation like this:
SELECT Table1.ID, Sum([A]+[B]+[C]) AS TotSum
FROM Table1
GROUP BY Table1.ID
ORDER BY Sum([A]+[B]+[C]) DESC;
Is there a way around this? It seems inefficient to recompute the sum 2 times where I think I only need to do it once.
Any input or explanations?
-BT.
View Replies
ADVERTISEMENT
Mar 6, 2008
I am currently making a project as part of my Computing course. The project is a running diary, where users can log in and record their running times(Amongst other things). As part of the system i am going to include a calorie calculator, to do so i have to work out the BMI (Body Mass Index). To do this you have to divide the weight by the square of the height. The weight and height are stored in the tables.
I am planning on creating a form for this conversion which will refer to a query. When the users log-in their ID is stored in a Public Variable called "UserID".
What i would like to do is query the database for their height and weight using this variable, but i don't know how to go about doing this.
Does anyone have any suggestions?
Many Thanks
View 6 Replies
View Related
Mar 21, 2006
I've built a pretty extensive database for work thanks largely to the folks on this board. But I'm stuck. I have a report to track inspections and it works fine, but I'd like to filter it down by AFSC (a coded expression the AF uses to denote career fields, i.e. 2A5x1x is Aircraft Maintenance.) The report's queries come from a couple of sources to retrieve the requirements for the report. For instance that AFSC has to start w/ "2A" and the labor code needs to start w/ "1" and not be "120". No problem. The problem I'm having is that the first 'x' (from the AFSCs below) is based on skill level (can be a 1, 3, 5, 7, or 9) and the last x is sometimes there and somtimes isn't.
For this particular report I've broken down the AFSCs down to three different formats. They are as follows:
2A5x1x (i.e. 2A531B or 2A571)
2A5x3x (i.e. 2A533A, 2A55B, 2A57C)
2A6(or 7)x1(or 2,3,4,5,or 6)
The report is designed to show who is due an inspection and it works fine. But I need to try to make it a little more user friendly so that all the various workcenters can trim it down to view just their career fields. Right now it reads from a query.
Here's the SQL for it.
SELECT qryPEDueUnion.[Main Assessee], [Employee List Table].[Employee RANK], [Employee List Table].[Employee NAME], [Employee List Table].AFSC AS FilterAFSC, [Employee List Table].[Labor Code] AS FilterLaborCode, qryPEDueUnion.[Inspection Type], Last(qryPEDueUnion.Date) AS LastOfDate
FROM qryPEDueUnion LEFT JOIN [Employee List Table] ON qryPEDueUnion.[Main Assessee] = [Employee List Table].EMP
GROUP BY qryPEDueUnion.[Main Assessee], [Employee List Table].[Employee RANK], [Employee List Table].[Employee NAME], [Employee List Table].AFSC, [Employee List Table].[Labor Code], qryPEDueUnion.[Inspection Type], Left([AFSC],2), Left([Labor Code],1)
HAVING ((([Employee List Table].[Labor Code])<>120) AND ((qryPEDueUnion.[Inspection Type])="PE") AND ((Last(qryPEDueUnion.Date)) Between DateAdd("m",-19,Now()) And DateAdd("m",-15,Now())) AND ((Left([AFSC],2))="2A") AND ((Left([Labor Code],1))=1))
ORDER BY Last(qryPEDueUnion.Date);
Let me know if you need more info. I'm new to posting on this board and haven't quite found out how to attach files....Plus this db is pretty big and I'd have to fool around w/ a copy of it first to make it small enough to attach.
View 3 Replies
View Related
Feb 22, 2007
Dear All,
I am trying to perform a SELECT query in access vba to show me customer account numbers in a msgbox.
I get a Run-time error '13': Type mismatch.
I would appreciate any help. Please see below for examples of my code.
'CustomerID is a Global Variable that gets it's value from a DLookup that gets triggered after a combobox has been selected.
The combobox does the following
'===START==================
Private Sub AfterUpdate_cboCustomer
Dim iCustID as Integer
iCustID = DLookup("ID", "tblCustomers", "Customer='" & Me.cboCustomer & "'")
iCustID = CustomerID
'Returns the Customer's ID Perfect
'=========START==============
Dim strSQL As String
strSQL = "SELECT AccNo FROM tblAccNo WHERE CustID" = CustomerID
DoCmd.RunSQL(strSQL)' Errors Here
'=======END==================
End Sub
'========END=============
View 4 Replies
View Related
Apr 11, 2008
I've created a rather simple Access program that I use to import an employee's cookie summary txt file. I then sort the cookies for 1) time of day, and 2) appropriateness.
I found a way to create the queries - in simple design mode using criteria - but I want system administrators in other offices to be able to enter the time of day variables particular to their offices. Same with appropriate words. So I want a form they can use to do that - eg, list their office's break times. In essence, a setup page. Then the resulting queries (time of day and word list) will be customized to the particulars of that office rather than to mine.
Would appreciate some ideas on how to do this. Should I read up on SQL? Should I learn VBA? I'm trying to get around having to tell the other system administrators to go into each query and change the criteria manually.
Thanks!
View 6 Replies
View Related
Aug 15, 2007
i have this query that i have several buttons that trigger it. how do i pass over a unique variable with each button. each button needs to append a different event. right now i have it set static to "3rd Party Denial" but i need that to be dynamic based on which button is pressed. PLEASE HELP!!!!!!
Code:INSERT INTO [Status Log] ( Status, Edit_Date, Event, Claim_ID )SELECT [Status Lookup].Status, Now() AS Expr1, "3rd Party Denial" AS Expr3, [Claim Report Info].[Claims Header].Claim_IDFROM [Status Lookup] RIGHT JOIN ([Claim Report Info] LEFT JOIN [Status Log] ON [Claim Report Info].[Claims Header].Claim_ID = [Status Log].Claim_ID) ON [Status Lookup].status = [Status Log].StatusGROUP BY [Status Lookup].Status, Now(), "3rd Party Denial", [Claim Report Info].[Claims Header].Claim_IDHAVING ((([Status Lookup].Status)=[Forms]![claiminformation]![ReportForm]![reportstatus1]) AND (([Claim Report Info].[Claims Header].Claim_ID)=[Forms]![claiminformation]![ReportForm]![Report_ClaimID]));
currently i have a macro running when clicked.
that macro runs 2 quieres and a report.
i'm doing this because thats the only way i know how.
View 7 Replies
View Related
Dec 22, 2011
I have a table that contains dates (Saturday through Friday). When I set up my query, I would like data returned where the date in a field is between the Saturday date and Friday date. Is there anyway to do this n the query without hard coding the dates in and manually changing the dates every week?
View 1 Replies
View Related
May 18, 2015
I understand I cannot easily run a SELECT * WHERE ... query in VBA ?
I want to run a simple Select query but use variables from the Form vba for the WHERE clause selections.
View 14 Replies
View Related
Feb 25, 2014
My problem is as follows, i have created a report that calculates the total volume of FSC Materials. The user picks two dates from Calender controls that the report will range from. However the needs have now changed and i am required to make the report filter further based on user input, the problem i'm facing is that i cannot figure out a way to pass values from different variables to the report separate from another here is the code i would usually use to pass data to a query/report:
Code:
Private Sub MonthlyFSC_Click()
Msg = MsgBox("Select the Start and Finish Dates you wish to Query.", , "Start / Finish")
Start = adhDoCalendar()
Finish = adhDoCalendar()
[Code] ....
However i am now trying to do this, but it gives me an error as it is trying to pass the values to one field:
Code:
Msg = MsgBox("Select the Start and Finish Dates you wish to Query.", , "Start / Finish")
Start = adhDoCalendar()
Finish = adhDoCalendar()
sql1 = "[ORDER DATE]<#" & Format(Finish, "MM/DD/YY") & "#"
sql2 = "[ORDER DATE]>#" & Format(Start, "MM/DD/YY") & "#"
[code]....
It is performing incorrectly within the case select and passing the wrong criteria, as it will only display results that meet the default values' criteria. However the date criteria is not be passed either.
View 4 Replies
View Related
Sep 29, 2014
Access 2010 vba - I'm trying to pass a start date and end date to a date field in a make table query, and use the 'between' operator on that date field.
So I have a criteria on the date field like this "Between [dtStart] and [dtEnd]" and if I run the query manually it asks for 2 values and then works fine.
Here's the code I'm trying to run:-
Set qdef = db.QueryDefs("qryTest")
qdef.Parameters("dtStart") = StartDate1
qdef.Parameters("dtEnd") = EndDate1
Set rs1 = qdef.OpenRecordset(dbOpenDynaset, dbSeeChanges)
and I get the error "3219 Invalid Operation" on the last line.
View 2 Replies
View Related
Aug 8, 2013
I am having a problem with a Dlookup query. I want to achieve the following - I have 2 different tables
Demography Table - consisting of 2 fields, City and Region
For example
City Region
NYC NAM
The other Table totalflow consists of several field, one of the is flow from.
For example
Flow from
NYC
WAS
SEA
I want to do the following. Lookup the Flow from filed in table totalflow, and compare it to City in demography Table. If City = Flow from, return the value in Region. All are text fields.
I have tried following Query, but it only returns the same value for all rows. (from SQL view)
SELECT DLookUp("[Region]","Demography Table","[City] = '" &[Flow from]& "'") AS test
FROM [Demography Table], flowsize;
View 3 Replies
View Related
Aug 8, 2013
I am trying to count rows in the result of one of the queries and I am having a bit of trouble getting it going.
The current code - this is executed as on-click event when clicked on List Box feed with query below.
What I want to add is simple if that when number of rows produced by the querry is 1 it will enable a picture item in the different part of the form, however it does not want to count the rows for me.
Code:
Private Sub search_items_Click()
Me.OBSFullFilledOrdersHolder.Enabled = True
mysql = "SELECT orders.[order id] , STUDENTS.[first name]& ' ' & students.[surname] AS Name, students.[contact name] AS ContactName , ORDERS.[Online Bookshelf order] AS OBS , STUDENTS.[Delivery Address 1], STUDENTS.[Delivery Address 2], STUDENTS.[Delivery Address 3], STUDENTS.[Delivery Address 4]"
[Code] ....
The query itself works when tested but when used in code with DCount function will return error: Run-Time 2471 the expression you entered as query parameter prouced this error
'[Forms]![FULLFILL ORDERS]![search items].[Column(0)]'.
View 5 Replies
View Related
Sep 28, 2005
I am really stuck. I have spent two days searcinh different forums trying to solve my problem. I am trying to create an UPDATE q to my Access database. But I get either the: "Syntax error in query. Incomplete query clause" or "Syntax error in UPDATE query".
First of all here's the URL: www.innotec-as.no/login/Kunder
Login U/P either: "alfen" or "thomas".
The page opening up shows the user info, U/P and adress.
viewing the information is working perfectly - but editing it..no way.
When editing and submiting the data the above errors occour.
Try that and you'll also see the SQL I am trying to execute.
The CODE is as follows:
SQLtemp = "UPDATE 'Brukere' SET"
SQLtemp = SQLtemp & " 'navn' = '" & request("Navn") & "', "
SQLtemp = SQLtemp & " 'epst' = '" & request("Epst") & "', "
SQLtemp = SQLtemp & " 'Pass' = '" & request("Pass") & "', "
SQLtemp = SQLtemp & " 'Firma' = '" & request("Firma") & "', "
SQLtemp = SQLtemp & " 'BAdresse' = '" & request("BAdresse") & "', "
SQLtemp = SQLtemp & " 'BPostAdr' = '" & request("BPostAdr") & "', "
SQLtemp = SQLtemp & " 'PAdresse' = '" & request("PAdresse") & "', "
SQLtemp = SQLtemp & " 'PPostAdr' = '" & request("PPostAdr") & "', "
SQLtemp = SQLtemp & "WHERE 'Bnavn' = '" & request("Bnavn") & "'"
Response.Write(SQLtemp)
Response.End()
conn.Execute(SQLtemp)
rs.Update[/COLOR]
The finished SQL statement looks like this:
UPDATE 'Brukere' SET 'navn' = 'Alf Byman', 'epst' = 'alf@baccara.no', 'Pass' = 'alfen', 'Firma' = '', 'BAdresse' = '', 'BPostAdr' = '', 'PAdresse' = 'sdfg', 'PPostAdr' = '', WHERE 'Bnavn' = 'alfen'
I have tried to user single quotes, doubble quotes, brackets etc. nothing works.
The code I use for connection is as follows:
<!--#include file="../adovbs.inc"-->
<%
dim conn, rs, SQLtemp
' DSNless connection to Access Database
set conn = server.CreateObject ("ADODB.Connection")
rs="DRIVER={Microsoft Access Driver (*.mdb)}; "
rs=rs & "PWD=uralfjellet; DBQ=" & server.mappath("../../../../db/kunder.mdb")
conn.Open rs
I'll be very HAPPY for some expert help on this.
View 1 Replies
View Related
Jul 20, 2006
I keep on getting a syntax error on the first [MU_ID]. Can anyone tell me what am I doing wrong please? You can e-mail me at Frank.Cappas@CIGNA.Com
Site: IF [MU_ID] BETWEEN ((SELECT [MU_Start] FROM [Sites] WHERE [Site] = “BRB”) AND (SELECT [MU_End] FROM [Sites] WHERE [Site] = “BRB”), “BRB”, {IF [MU_ID] BETWEEN ((SELECT [MU_Start] FROM [Sites] WHERE [Site] = “BRI”) AND (SELECT [MU_End] FROM [Sites] WHERE [Site] = “BRI”},"BRI")
Thank you so much in advance,
Frank
View 1 Replies
View Related
Dec 6, 2006
I'm trying to get my head round this query and not having much luck.
I have table that contains. amongst others, two fields I need to use - Date and Amount. I already have a query that returns me the number of entries for a given month, along with the total value.
SELECT Count(*) AS [Number of Entries],
Sum(NBReferral.[Amount]) AS [Total Amount],
NBReferral.Date
FROM NBReferral
GROUP BY NBReferral.Date;
What I want is to also provide a running total (year to date). Using this:
SELECT Count(*) AS [YTD Number of Entries],
Sum(NBReferral.[Amtount]) AS [YTD Total Amount]
FROM NBReferral;
Combing the two queries works as long as there is only one month. Unfortunately, I'd like to see each month's YTD figure displayed as shown
Date Number of Entries Total Amount YTD Number of Entries YTD Total Amount
Nov 2006 5 10000 5 10000
Dec 2006 3 5000 8 15000
Jan 2007 6 12000 14 27000
etc.
What I currently get, as you would expect, are the same YTD totals applied to each month:
Date Number of Entries Total Amount YTD Number of Entries YTD Total Amount
Nov 2006 5 10000 14 27000
Dec 2006 3 5000 14 27000
Jan 2007 6 12000 14 27000
etc.
Probably a fairly straight-forward query for someone with a bit more experience. Any ideas?
View 3 Replies
View Related
Mar 27, 2008
Hi all,
I have the following code that works really well for me:
Me.lstEngines.RowSource = "Select [Engine Name], [Type], [Engine #] " & _
"From [Main Data Entry] " & _
"Where [Engine Name] like '*" & Me.txtsearch & "*'"
Me.lstEngines.Requery
I need to make one modification to it, but I am getting lost in the syntax.
Right now this code is matching the text string "txtsearch" to anything in the "Engine Name" Field.
It works fine, but I need it to also look in the "type" field. I need results if the string is in "Engine Name" OR if it is in "Type"
How do I do that?
Thanks
View 5 Replies
View Related
Oct 19, 2004
I want to run a query that allows the user to enter the beginning date and the ending date to produce the results for all items within those dates. I've written this before using "Between", but I can't get the syntax correct.
HEEELLLLLLPPPPPPPPPP
thanks
View 1 Replies
View Related
Feb 28, 2006
HI,
Is it possible to have space in an field name (Column name) when I using a Query?
ex:
UPDATE tblBlocks SET Block Description = Text
WHERE (Category = x1 & Name = x2 & Block Type = x3);
I get an syntax error on this "Block Description" but not if i write BlockDescription...
Anyone?
I use Access97
Regards Hans
View 2 Replies
View Related
Aug 19, 2005
I have the following sql that returns my sample records:
SELECT QryAllEnrolments.[Person Id], QryAllEnrolments.[Course Code], QryAllEnrolments.[Course Name], QryAllEnrolments.GLH, QryAllEnrolments.Date
FROM QryAllEnrolments LEFT JOIN QryWithdrawls ON (QryAllEnrolments.[Person Id] = QryWithdrawls.[Person Id]) AND (QryAllEnrolments.[Course Code] = QryWithdrawls.[Course Code])
WHERE (((QryAllEnrolments.[Person Id])=1950165) AND ((QryWithdrawls.[Person Id]) Is Null));
and wrote the following hoping it would return a running sum of the guided learning hours (GLH) utilising the above:
SELECT Pro.[Date], Pro.[Person Id], Pro.[Course Code], Pro.[Course Name], Pro.[GLH],
(Select Sum(Pro1.[GLH] FROM [QryAllEnrolments Without Matching QryWithdrawls] Pro1 WHERE Pro1.[Date]<=Pro.[Date]) AS [Running Total], Pro.[Date]
FROM [QryAllEnrolments Without Matching QryWithdrawls] AS Pro
ORDER BY Pro.[Date]
It squeels of a syntax error at the inner select sum clause.
your assistance to finish this off would be greatly appreciated.
regards
Peter
View 8 Replies
View Related
Sep 28, 2005
I keep getting a syntax error (missing operator) with this bit of code when executing SQL in VBA.
"WHERE [tbl_Student_Roster].[Student Name]= " & [Forms]![form_Student_Roster]![Student_Name] & ";"
It is part of a larger piece, but the rest works (or does not give me an error).
Any ideas?
Thanks.
View 2 Replies
View Related
Sep 12, 2006
I'm new to Access and have been learning how to use it for the better part of a year. I've done all the Microsoft online tutorials relevant to the work I need to do with it, and gotten a few books out of the library besides. In general, I self-teach very well given a good resource.
Here's my problem: the main area in which I need to be proficient is running queries, and I cannot find a good, comprehensive explanation of how to construct expressions or set up calculated fields.
In case I'm not clear (I've had quite a time just figuring out what to call what I need), I'll give you an example. I was able to arrange a short tutorial with someone in another department. As part of a query, she used the following statement in the "Field" section to convert date information stored as mm/dd/yyyy into just the year:
Year: IIf([referraldate]<#1/1/2003#,"2002",IIf([referraldate] Between #12/31/2002# And #1/1/2004#,"2003",IIf([referraldate] Between #12/31/2003# And #1/1/2005#,"2004",IIf([referraldate] Between #12/31/2004# And #1/1/2006#,"2005",IIf([referraldate] Between #12/31/2005# And #1/1/2007#,"2006")))))
This is the kind of thing I want to learn how to do. Unfortunately, the Microsoft tutorials don't do much more that give examples of different expressions and functions; I feel like I've been given a handful of sample sentences, a few nouns, and a few verbs--and then told to go speak English.
What I need is a comprehensive guide that not only gives me the building blocks of expressions, but tells me how to combine them into a syntactically meaningful statement--so I know what order things go in, where commas and parentheses should be, etc. Both online or print materials are fine--I've been looking on my own, but with no luck.
Thanks for your help!
View 5 Replies
View Related
Apr 24, 2008
I have a select query with a number of expressions and I cannot seem to get the expressions to work. Access keeps giving me syntax error on the following code:
SELECT Run.Test_Case,
Sum(IIf(DateValue([Attempted_Actual]) < DateValue([Attempted_Actual]),[Points],0))/Sum(IIf(Not IsNull([Attempted_Actual]),[Points],0))*100 AS ActualAttempted,
Sum(IIf(DateValue([Completed_Actual]) < DateValue([Completed_Actual]),[Points],0))/Sum(IIf(Not IsNull([Completed_Actual]),[Points],0))*100 AS ActualCompleted,
Sum(IIf(DateValue([Verified_Actual]) < DateValue([Verified_Actual]),[Points],0))/Sum(IIf(Not IsNull([Verified_Actual]),[Points],0))*100 AS ActualClosed,
Sum(IIf(DateValue([Attempted_Planned]) < DateValue(Date()),[Points],0))/Sum(IIf(Not IsNull([Attempted_Planned]),[Points],0))*100 AS PlannedAttempted,
Sum(IIf(DateValue([Completed_Planned]) < DateValue(Date()]),[Points],0))/Sum(IIf(Not IsNull([Completed_Planned]),[Points],0))*100 AS PlannedCompleted,
Sum(IIf(DateValue([Verified_Planned]) < DateValue(Date()),[Points],0))/Sum(IIf(Not IsNull([Verified_Planned]),[Points],0))*100 AS PlannedClosed
FROM Run INNER JOIN Task ON Run.Run=Task.Group
GROUP BY Run.Test_Case;
HAVING (((Run.Test_Case)=IIf(IsNull([Forms]![Status]![ComboStatusTestCase]),[Test_Case],[Forms]![Status]![ComboStatusTestCase])));
I am sort of confused on where the error could because it just says there is a syntax error. My assumption is that I am using DateValue() in the wrong context. If anyone has any pointers or sees my error please let me know.
Thanks,
View 3 Replies
View Related
Apr 30, 2008
I've been staring at this for a while and have had no luck, anyone able to assist?
Dim Conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sql As String
Set Conn = CurrentProject.Connection
Set rs = New ADODB.Recordset
sql = "INSERT INTO COMMENTS (TXT,MODIFIED,PID,P_SCHEDULE,P_BUDGET,P_SCHEDUAL_C OM,P_BUDGET_COM) Values (" & Forms!PROJECT_EDIT!comments & ", Now() , " & Forms!PROJECT_EDIT!PID & " , '" & P_SCHEDULE_VAR & "' , '" & P_BUDGET_VAR & "' , '" & Forms!PROJECT_EDIT!P_SCHEDUAL_COM & "' , '" & Forms!PROJECT_EDIT!P_BUDGET_COM & " ' ;)"
Conn.Execute sql
The error is point it too the end of the document
Thanks in advanced
View 8 Replies
View Related
Jul 12, 2005
Can someone tell me where I might be going wrong here. The following query works in SQL, but somewhere in the LEFT JOINS area, Access gets a little confused and says I'm missing an operator.
SELECT Tariffs.TariffCPUCID, Tariffs.TariffID, AdviceLetters.ALCPUCID, Tariffs.ALID, Tariffs.ScheduleID, Schedules.SheetTitle, AdviceLetters.[Filing Date], Tariffs.[C&E], SheetsCancelling.CancellingID, SheetsCancelling.CancellingCPUCID
FROM Tariffs LEFT JOIN Schedules ON Tariffs.ScheduleID = Schedules.ScheduleID LEFT JOIN AdviceLetters ON Tariffs.ALID = AdviceLetters.ALID LEFT JOIN SheetsCancelling ON SheetsCancelling.TariffID = Tariffs.TariffID
WHERE Tariffs.Type="E"
ORDER BY Tariffs.TariffCPUCID DESC;
View 5 Replies
View Related
Sep 6, 2006
Can someone tell me the VBA code for testing whether a query recordset is empty or not?
View 1 Replies
View Related
Sep 17, 2007
Hello, first time posting, not sure what info you all need. I'm looking for some help with an if/then statement in access query involving dates. Below is the query I am trying to use, along with the error message. Any ideas?
Domestic Violence CME Required?: IIf(([Date of Next Medical License Renewal]-[Date of Last Domestic Violence Credit (2)])>("yyyy",6),"yes","no")
syntax error (comma) in query expression 'IIf(([Date of Next Medical License Renewal]-[Date of Last Domestic Violence Credit (2)])>("yyyy",6),"yes","no")'
The error seems to be in relationship to the number 6. I want a "yes" to show up in the field if the difference is greater then 6 years.
View 2 Replies
View Related