initialize a parameter in MS Access query - ms-access

In MS Access 2010 I am trying to declare and initialize a variable in a query, then display the contents of that variable. The reason for doing this is to use the parameter in a more complicated query as part of a filter. Please note that for this particular case this task must be done in a query object, not in VBA. Here is the code thus far:
PARAMETERS #Date DATE;
SELECT TOP 1 FORMAT(LastUpdated, "yyyy-mm-dd") AS #Date FROM Table1 GROUP BY FORMAT(LastUpdated, "yyyy-mm-dd") ORDER BY FORMAT(LastUpdated, "yyyy-mm-dd") DESC;
SELECT #Date;
This results in an error message: "Characters found after end of SQL statement."
If this can be modified to work the last line of code will be replaced with the more complex query that needs to use #Date in a filter. The other requirement is that it has to be contained within one query object.

In Access you don't need to use the # to prefix parameters. Parameters are inferred as any column which cannot be resolved. So if your table does not have a date column then using date is sufficient for "declaring" a parameter. However maybe something like p_date can separate it from the data type DATETIME/DATE
I don't know what exactly you are expecting with this
FORMAT(LastUpdated, "yyyy-mm-dd") AS #Date
It seems to be trying to assign an alias to FORMAT(LastUpdated, "yyyy-mm-dd") as the parameter value of #Date?
An Access query cannot return multiple result sets so your SELECT #Date; is ultimately what is causing the "Characters found after end of SQL statement." error message.

Related

SSRS dataset filter

Hi I'm trying to build a report in ssrs which gives the output based on current weekending date where end day is saturday. I'm pulling my data from SSAS Cube and I have a weekending date field so I applied a filter in the query designer to get the current weekending date using a parameter I used this expression:
DateAdd("d",7-DatePart(DateInterval.Weekday,Today,FirstDayOfWeek.Sunday),Today)
When I'm executing my query, it throws an error saying the restriction imposed by the constrained flag in the STRTOSET function were violated.
Please let me know how can I fix this.
The error is thrown because you are passing a string that doesn't correspond with a valid member in your cube.
Note the Query Designer builds a MDX query based on the dimensions and members you select, this query uses the STRTOSET() function to convert your string parameter in a valid member.
...
STRTOSET(#CurrentWeekendDate,CONSTRAINED)
...
If you pass the current weekend date to your parameter it produces:
STRTOSET('2016-01-10',CONSTRAINED)
As 2016-01-10 is not a valid member in your Date dimension it throws the error.
You have to pass something like this depending on your cube:
[Date].[Date Key].&[2005-01-01T00:00:00]
So in SSRS you have to set your parameter to Text and use this expression:
CORRECT EXPRESSION:
="[200 Date].[Week Ending Date].&[" &
Format(
DateAdd("d",7-DatePart(DateInterval.Weekday,Today,FirstDayOfWeek.Sunday),Today),
"yyyy-MM-ddThh:mm:ss"
)
& "]"
UPDATE: If [Week Ending date] level doesn't include time:
="[Date].[Date Key].&[" &
Format(
DateAdd("d",7-DatePart(DateInterval.Weekday,Today,FirstDayOfWeek.Sunday),Today),
"yyyy-MM-dd"
)
& "]"
Go through this tutorial if you get stuck.
Let me know if this helps.

Calling a function from query criteria

I have viewed a lot of what others have asked and answered for this through Google, but have an additional question others haven't covered. My situation is that I am calling an Access query from AUTOMATE, a controller program. The process will run monthly against the data of the preceding month.
My intent is to use two functions declared in a module within Access to put the date range in the WHERE clause, but am finding putting it in on the query criteria line seems to be a problem.
Here are the two functions:
'##################################################################################
' This function returns the date string for the first day of the prior month.
'##################################################################################
Public Function FirstDayPriorMonth() As Date
Dim dateEnd As Date
dateEnd = DateSerial(Year(Date), Month(Date), 0)
FirstDayPriorMonth = dateEnd - Day(dateEnd) + 1
End Function
'##################################################################################
' This function returns the date string for the last day of the prior month.
'##################################################################################
Public Function LastDayPriorMonth() As Date
LastDayPriorMonth = DateSerial(Year(Date), Month(Date), 0)
End Function
The call from AUTOMATE uses DoCmd.OpenQuery to call the query. The SQL version of the full query looks like this:
SELECT dbo_V_HB_Outsourced_AR.REPORTING_DATE,
dbo_V_HB_Outsourced_AR.REPORTING_FISCAL_YEAR AS FY,
dbo_V_HB_Outsourced_AR.LOC_NAME AS FACILITY,
dbo_V_HB_Outsourced_AR.REVCBO_LEGACY_FINANCIAL_CLASS,
dbo_V_HB_Outsourced_AR.EPIC_FINANCIAL_CLASS,
dbo_V_HB_Outsourced_AR.PRIMARY_FIN_CLASS_NAME,
dbo_V_HB_Outsourced_AR.ACCT_STATUS_NAME,
dbo_V_HB_Outsourced_AR.OUTSOURCED_FLAG_YN,
dbo_V_HB_Outsourced_AR.IN_HOUSE_FLAG_YN,
dbo_V_HB_Outsourced_AR.DNFB,
dbo_V_HB_Outsourced_AR.[0-30],
dbo_V_HB_Outsourced_AR.[31-60],
dbo_V_HB_Outsourced_AR.[61-90],
dbo_V_HB_Outsourced_AR.[91-120],
dbo_V_HB_Outsourced_AR.[121-150],
dbo_V_HB_Outsourced_AR.[151-180],
dbo_V_HB_Outsourced_AR.[181-210],
dbo_V_HB_Outsourced_AR.[211-240],
dbo_V_HB_Outsourced_AR.[241-365],
dbo_V_HB_Outsourced_AR.[366+],
dbo_V_HB_Outsourced_AR.[CR BAL],
dbo_V_HB_Outsourced_AR.[Total (Debit Only)],
dbo_V_HB_Outsourced_AR.[Over 90],
dbo_V_HB_Outsourced_AR.COL_AGNCY_NAME
FROM dbo_V_HB_Outsourced_AR
WHERE (((dbo_V_HB_Outsourced_AR.REPORTING_DATE) Between [FirstDayPriorMonth] And [LastDayPriorMonth])
AND ((dbo_V_HB_Outsourced_AR.COL_AGNCY_NAME)='ADVICARE'
Or (dbo_V_HB_Outsourced_AR.COL_AGNCY_NAME)='CONVERGENT'
Or (dbo_V_HB_Outsourced_AR.COL_AGNCY_NAME)='MEDALIST MANAGEMENT')
AND ((dbo_V_HB_Outsourced_AR.LOC_ID)=1010
Or (dbo_V_HB_Outsourced_AR.LOC_ID)=1011
Or (dbo_V_HB_Outsourced_AR.LOC_ID)=1012
Or (dbo_V_HB_Outsourced_AR.LOC_ID)=1013
Or (dbo_V_HB_Outsourced_AR.LOC_ID)=1014));
My question is why can I see the function calls on the query criteria line, but have to change the query in the SQL view? I am still working on getting the function calls to work in the SQL view as well.
I am calling an ACCESS query from AUTOMATE, a controller program.
Unfortunately, a query run from outside an Access application session can not use VBA user-defined functions. That means your FirstDayPriorMonth and LastDayPriorMonth functions are not available in that situation.
Fortunately both those functions are based on fairly simple DateSerial expressions, and DateSerial is usable in any Access query regardless of whether the query is run from within or outside an Access session.
So instead of this ...
Between [FirstDayPriorMonth] And [LastDayPriorMonth]
Use this ...
BETWEEN DateSerial(Year(Date()), Month(Date()) -1, 1)
AND DateSerial(Year(Date()), Month(Date()), 0)
"<first part of query>
from dbo_V_HB_Outsourced_AR
WHERE (((dbo_V_HB_Outsourced_AR.REPORTING_DATE) Between #" & FirstDayPriorMonth() & "# and #" & LastDayPriorMonth() & "#" &
"rest of query"
You need to construct your query string by concatenating the results of the function calls (which should not be in square brackets as they are not field names). Also, dates need a "#" side on each side (in MS-Access).

Getting Error When Using Parameter Variable in Access

I am getting an error when running a query in Access that states that my expression is incorrect or too complex. I am trying to filter a query with a parameter [Report Date] on a DateValue expression. The query runs without the parameter, unfiltered of course. It will work if I create a table and write a new query with the parameter but this will need to be run daily and that seems cumbersome. Syntax below:
SELECT tbl_ReturnedEquipment.DateProgrammed, DateValue([tbl_ReturnedEquipment]![DateProgrammed]) AS Expr1, tbl_ReturnedEquipment.CSID, tbl_ReturnedEquipment.NewID
FROM tbl_ReturnedEquipment
WHERE (((DateValue(tbl_ReturnedEquipment!DateProgrammed))=[Report Date]) And ((tbl_ReturnedEquipment.NewID) Is Not Null) And ((tbl_ReturnedEquipment.EquipType)=2));

How to convert separate date and time parameters to a valid datetime?

I have a report with date and time (only an hour and minutes) parameters which are separate. The Date parameter is of type Date/Time, and the Time parameter is set as Text. I want to merge those two values into one because I want to pass a minimum number of arguments to the stored procedure. I tried to achieve that goal in many ways but SSRS returns an error for every attempt.
If I try to use expression like this:
=Format(FormatDateTime(Parameters!startDate.Value, DateFormat.ShortDate).ToString() + Parameters!startTime.Value, "dd/MM/yyyy HH:mm")
SSRS returns this error:
Error conterting data type nvarchar to datetime.
And when I tried to use Datetime.Parse like this:
=DateTime.Parse(Format(FormatDateTime(Parameters!startDate.Value, DateFormat.ShortDate).ToString() + Parameters!startTime.Value, "dd/MM/yyyy HH:mm"))
SSRS said:
The Value expression for the query parameter '#startDate' contains an error: The string was not recognized as a valid DateTime. There is a unknown word starting at index 0.
When I removed the FormatDateTime function I get yet another error:
The Value expression for the query parameter '#startDate' contains an error: Input string was not in a correct format.
Do you have any ideas how to write this expression correctly?
PS. I use SSRS 2008 R2.
This works for me:
=CDate(Format(Parameters!Date.Value, "yyyy-MM-dd") + " " + Parameters!Time.Value)
Didn't try and troubleshoot your specific examples, but they may be running into issues where you're not including the space between the date and time.
The above expression may be suitable for your report; don't know robust it would be in different locales.
You could also consider doing the concatenation/conversion in custom code if you need more flexibility.

Fields cannot be used in report parameter expression

I have to set the start_date of my report depending of a report parameter. The time stamps are calculated in a database query.
My expression looks like this:
=SWITCH (
Parameters!report_type.Value = 1,First(Fields!daily_start.Value, "Timestamps")
,Parameters!report_type.Value = 2,First(Fields!weekly_start.Value, "Timestamps")
,Parameters!report_type.Value = 3,First(Fields!monthly_start.Value, "Timestamps")
)
Unfortunately I get the error message:
A value expression used for the report parameter 'time_from' refers to a field. Fields cannot be used in report parameter expression
I know, that this is not allowed because SSRS cannot be sure in which order datasets are called. But I think this is not dangerous.
All time stamps are received by query without parameter. The parameter report_type is selected by a user before the report will be generated.
Can someone give me a hint for a workaround?
Here's the workaround - get the value using SQL.
Create a new Dataset called StartDates:
SELECT CASE
WHEN #report_type = 1 THEN daily_start
WHEN #report_type = 2 THEN weekly_start
WHEN #report_type = 3 THEN monthly_start
END AS StartDate
FROM MyTable
You already have the #report_type and #time_from parameters. With the #time_from parameter, set its Default Values to Get values from a query using the StartDates dataset and the Value field StartDate.
Now, you'd think this might be enough to make it work - you're referencing this query as the default value and as you change the #report_type parameter the other parameters refresh, but the first date in the #time_from parameter never changes. That's because the refresh happens on the Available Values query, not on the Default Values query.
So you also need to wire up the Available Values query to the StartDates query. Now your query will fire on the change of #report_type and the default value will be set to the appropriate date for your selection.
I switched from a query to Stored Procedure and was getting this error. Things I tried:
Ensured I had sufficient permission on the database (you need EXEC rights or DBO to run teh sproc)
Delete the existing parameters (and then use refresh fields to refresh/get the correctly named ones back)
Remove the square brackets around the stored procedure if you've specified that
Sometimes, Expressions can get a bit verbose. I have created a Report Code Function and then used that as the Parameter Value.
For example, I created a Code function called "CalculateDateSet" and then set the Report Parameter to this expression:
"=Code.CalculateDateSet(Parameters!Month.Value, Parameters!Year.Value"