Random number using Date() in Expression Builder - ms-access

I want to generate random number using Date() to format it like for example: ddmmyyyyHhNnSs
How do I achieve that? Is that even possible?
I was kinda hoping I can do it easy way by the expression builder but I seem to fail on each approach ;)
This number need to populate txtID field and it will be unique identifier for each database entry.

That's quite easy - with a twist.
Problem is that Rnd only returns a Single and the resolution of this only allows for 10000000 unique values. As you request a resolution to the second and with 86400 seconds per day, that only leaves a span of 115.74 days while the range of Date spans 3615899 days:
TotalDays = -CLng(#1/1/100#) + CLng(#12/31/9999#)
To overcome this, use Rnd twice which will result in 1E+15 possible values or 11574074074 days - way beyond what's needed:
RandomDouble = Rnd * Rnd
Now, to limit the possible values to fit into the range of data type Date, just follow the documentation:
RandomValue = (UpperValue - LowerValue) * Rnd + LowerValue
and apply the date values:
RandomDouble = (CLng(#12/31/9999#) - CLng(#1/1/100#)) * Rnd * Rnd + CLng(#1/1/100#)
This, however, will result in values containing unwanted milliseconds, thus perform the proper conversion to Date value using CDate which will round to the nearest second, and you have the final expression:
RandomDate = CDate((CLng(#12/31/9999#) - CLng(#1/1/100#)) * Rnd * Rnd + CLng(#1/1/100#))
Use the value as is if your field is of datatype Date or - if text - apply a format to this with Format(RandomDate, "yyyymmddhhnnss") and a sample output will be:
01770317032120
01390126010945
50140322081227
35290813165627
09330527072433
20560513105943
61810505124235
09381019130230
17010527033132
08310306233911
If you want numeric values, use CDec to convert (CLng will fail because of overflow):
RandomNumber = CDec(Format(RandomDate, "yyyymmddhhnnss"))
All said, I'm with #Bohemian - if you just want a unique timestamp and have less than one transaction per second, just use data type Date for your field and use Now:
TimeStamp = Now()
and apply a format to this of yyyymmddhhnnss.
However, Multiplying random numbers together alters the
probablility distribution:
Uniform Product Distribution
Thus, a better method is to create a random date, then a random time, and possibly a random count of milliseconds - I wrote above, that CDate rounds a value to the nearest second; it doesn't, only whenever Access displays a date/time with milliseconds the displayed valued is rounded to the second.
So I modified the function to take care of this:
Public Function DateRandom( _
Optional ByVal UpperDate As Date = #12/31/9999#, _
Optional ByVal LowerDate As Date = #1/1/100#, _
Optional ByVal DatePart As Boolean = True, _
Optional ByVal TimePart As Boolean = True, _
Optional ByVal MilliSecondPart As Boolean = False) _
As Date
' Generates a random date/time - optionally within the range of LowerDate and/or UpperDate.
' Optionally, return value can be set to include date and/or time and/or milliseconds.
'
' 2015-08-28. Gustav Brock, Cactus Data ApS, CPH.
' 2015-08-29. Modified for uniform distribution as suggested by Stuart McLachlan by
' combining a random date and a random time.
' 2015-08-30. Modified to return selectable and rounded value parts for
' Date, Time, and Milliseconds.
' 2015-08-31. An initial call of Randomize it included to prevent identical sequences.
Const SecondsPerDay As Long = 60& * 60& * 24&
Dim DateValue As Date
Dim TimeValue As Date
Dim MSecValue As Date
' Shuffle the start position of the sequence of Rnd.
Randomize
' If all parts are deselected, select date and time.
If Not DatePart And Not TimePart And Not MilliSecondPart = True Then
DatePart = True
TimePart = True
End If
If DatePart = True Then
' Remove time parts from UpperDate and LowerDate as well from the result value.
' Add 1 to include LowerDate as a possible return value.
DateValue = CDate(Int((Int(UpperDate) - Int(LowerDate) + 1) * Rnd) + Int(LowerDate))
End If
If TimePart = True Then
' Calculate a time value rounded to the second.
TimeValue = CDate(Int(SecondsPerDay * Rnd) / SecondsPerDay)
End If
If MilliSecondPart = True Then
' Calculate a millisecond value rounded to the millisecond.
MSecValue = CDate(Int(1000 * Rnd) / 1000 / SecondsPerDay)
End If
DateRandom = DateValue + TimeValue + MSecValue
End Function

Format now() and cast to a long:
select CLng(format(now(), 'ddmmyyyyhhnnss')) as txnId
Although this is not "random", it is unique as long as there are never more than one transaction per second (confirmed in comment above).

Related

DateDiff Calculate Age Incorrectly

In Microsoft Access I am using the DateDiff formula in a text box on a form to calculate a person's age. The user types the date of birth and another text box called “Age” calculates and displays the age based on that date of birth and today’s date. But for some reason the age is incorrect. Here is the formula I am using to determining age.
=DateDiff("yyyy",[txtDoB1],Date()) 'today is 2/12/2021
=DateDiff("yyyy", #5/24/1979#, #2/12/2021#) 'this has the dates manually typed in
The DateDiff formula returns 42 as the age. That is not correct. It should be 41. Why is the DateDiff formula resulting in an incorrect age? What am I doing wrong?
The following solution using DateDiff is from Microsoft. I have used it and it works well. The link is: https://learn.microsoft.com/en-us/office/vba/access/Concepts/Date-Time/calculate-age
Function Age(varBirthDate As Variant) As Integer
Dim varAge As Variant
If IsNull(varBirthDate) Then Age = 0: Exit Function
varAge = DateDiff("yyyy", varBirthDate, Now)
If Date < DateSerial(Year(Now), Month(varBirthDate), _
Day(varBirthDate)) Then
varAge = varAge - 1
End If
Age = CInt(varAge)
End Function
The DateDiff formula does not calculate the difference between years very well. If you use "yyyy" in the DateDiff formula then it only uses the year portion of the 2 dates provided in the formula to calculate the difference in years. This leads to undesirable results. In your example the DateDiff formula would take 2021 from 2/12/2021 and subtract it by 1979 from 5/24/1979. Or in other words, 2021 - 1979 = 42.
Instead try using the below formula.
=Int((Date()-[txtDoB1])/365.25) '365.25 compensates for leap years
=Int((#2/11/2021#-#5/24/1979#)/365.25)
DateDiff returns the difference in calendar years.
For calculating age correct for any dates, DateAdd must be used:
' Returns the difference in full years from DateOfBirth to current date,
' optionally to another date.
' Returns zero if AnotherDate is earlier than DateOfBirth.
'
' Calculates correctly for:
' leap years
' dates of 29. February
' date/time values with embedded time values
' any date/time value of data type Date
'
' DateAdd() is used for check for month end of February as it correctly
' returns Feb. 28th when adding a count of years to dates of Feb. 29th
' when the resulting year is a common year.
'
' 2015-11-24. Gustav Brock, Cactus Data ApS, CPH.
'
Public Function Age( _
ByVal DateOfBirth As Date, _
Optional ByVal AnotherDate As Variant) _
As Integer
Dim ThisDate As Date
Dim Years As Integer
If IsDate(AnotherDate) Then
ThisDate = CDate(AnotherDate)
Else
ThisDate = Date
End If
' Find difference in calendar years.
Years = DateDiff("yyyy", DateOfBirth, ThisDate)
If Years > 0 Then
' Decrease by 1 if current date is earlier than birthday of current year
' using DateDiff to ignore a time portion of DateOfBirth.
If DateDiff("d", ThisDate, DateAdd("yyyy", Years, DateOfBirth)) > 0 Then
Years = Years - 1
End If
ElseIf Years < 0 Then
Years = 0
End If
Age = Years
End Function

Renumbering sequence numbers

I would like to add a auto sequential number under STOP # field. I have fields as Route, Direction, Stop #, & location. So for example M1 going North has 10 stops (1-10) and vice versa for South bound.
You can use the RowNumber function from my article:
Sequential Rows in Microsoft Access
' Builds consecutive row numbers in a select, append, or create query
' with the option of a initial automatic reset.
' Optionally, a grouping key can be passed to reset the row count
' for every group key.
'
' 2018-08-23. Gustav Brock, Cactus Data ApS, CPH.
'
Public Function RowNumber( _
ByVal Key As String, _
Optional ByVal GroupKey As String, _
Optional ByVal Reset As Boolean) _
As Long
' Uncommon character string to assemble GroupKey and Key as a compound key.
Const KeySeparator As String = "¤§¤"
' Expected error codes to accept.
Const CannotAddKey As Long = 457
Const CannotRemoveKey As Long = 5
Static Keys As New Collection
Static GroupKeys As New Collection
Dim Count As Long
Dim CompoundKey As String
On Error GoTo Err_RowNumber
If Reset = True Then
' Erase the collection of keys and group key counts.
Set Keys = Nothing
Set GroupKeys = Nothing
Else
' Create a compound key to uniquely identify GroupKey and its Key.
' Note: If GroupKey is not used, only one element will be added.
CompoundKey = GroupKey & KeySeparator & Key
Count = Keys(CompoundKey)
If Count = 0 Then
' This record has not been enumerated.
'
' Will either fail if the group key is new, leaving Count as zero,
' or retrieve the count of already enumerated records with this group key.
Count = GroupKeys(GroupKey) + 1
If Count > 0 Then
' The group key has been recorded.
' Remove it to allow it to be recreated holding the new count.
GroupKeys.Remove (GroupKey)
Else
' This record is the first having this group key.
' Thus, the count is 1.
Count = 1
End If
' (Re)create the group key item with the value of the count of keys.
GroupKeys.Add Count, GroupKey
End If
' Add the key and its enumeration.
' This will be:
' Using no group key: Relative to the full recordset.
' Using a group key: Relative to the group key.
' Will fail if the key already has been created.
Keys.Add Count, CompoundKey
End If
' Return the key value as this is the row counter.
RowNumber = Count
Exit_RowNumber:
Exit Function
Err_RowNumber:
Select Case Err
Case CannotAddKey
' Key is present, thus cannot be added again.
Resume Next
Case CannotRemoveKey
' GroupKey is not present, thus cannot be removed.
Resume Next
Case Else
' Some other error. Ignore.
Resume Exit_RowNumber
End Select
End Function

SELECT Newest date based on Week and Year criteria

I think i have a simple problem, i just cant figure it out. I have a table with ID, Date and Value
I want to select the NEWEST value based on criteria of week and year. Meaning i only have the year and week to find the newest value.
if you do the following
SELECT TOP 1 Value from tbl WHERE year(Date)<=year and format(date,"WW")<= weeknumber
you get a problem. because if the year is 2020 and the week is 30. then if there is a value from the 31/12/2019 it wont return it because format(date,"WW") is greater than the week.
Example: dateformat=dd/mm/yyyy
ID Date Value
1 15/01/2019 15
2 31/12/2019 18
3 15/04/2020 19
if the week is 5 and the year is 2020
the result of the sql should be 18 since that is the newest value before the week and year. But the query i wrote above returns 15, which makes sence because of the week of 31/12/2019>5 and therefore wont be returned.
But how do i do this correctly?
As this probably is ISO 8601 week numbering, the year is not the calendar year but the ISO 8601 year, which native VBA knows nothing about, thus a custom function is needed:
' First day of the week.
WeekStart = DateYearWeek(5, 2020, vbMonday)
' WeekStart -> 2020-01-27
The function is not that convoluted:
' Returns the date of Monday for the ISO 8601 week of IsoYear and Week.
' Optionally, returns the date of any other weekday of that week.
'
' 2017-05-03. Gustav Brock, Cactus Data ApS, CPH.
'
Public Function DateYearWeek( _
ByVal IsoWeek As Integer, _
Optional ByVal IsoYear As Integer, _
Optional ByVal DayOfWeek As VbDayOfWeek = VbDayOfWeek.vbMonday) _
As Date
Dim WeekDate As Date
Dim ResultDate As Date
If IsoYear = 0 Then
IsoYear = Year(Date)
End If
' Validate parameters.
If Not IsWeekday(DayOfWeek) Then
' Don't accept invalid values for DayOfWeek.
Err.Raise DtError.dtInvalidProcedureCallOrArgument
Exit Function
End If
If Not IsWeek(IsoWeek, IsoYear) Then
' A valid week number must be passed.
Err.Raise DtError.dtInvalidProcedureCallOrArgument
Exit Function
End If
WeekDate = DateAdd(IntervalSetting(dtWeek), IsoWeek - 1, DateFirstWeekYear(IsoYear))
ResultDate = DateThisWeekPrimo(WeekDate, DayOfWeek)
DateYearWeek = ResultDate
End Function
but - as you can see - it calls some helper functions, which again call other functions, which will be too much to post here.
I can upload it somewhere, if you feel this will provide a solution for you.
There is no simple work-around. On the other hand, once held in a module, the code is simple to implement - as you can see.

Calculating Time Difference Exceeding 24 hours

I am having an issue where I am trying to calculate the time difference in seconds and then in a report (Access reports) I will sum those seconds and format it into hh:nn:ss.
However, my calculated field that gathers the time difference between the two fields sometimes exceeds 24 hours and thus throws off the time difference.
I am using the DateDiff function --- DateDiff("s",[BeginningTime],[EndingTime])
What should I do when it comes to circumstances where the time exceeds 24 hours?
The two fields, BeginningTime and EndingTime, are stored in the AM/PM format. I don't think that should matter though.
You can use a function like this:
Public Function FormatHourMinute( _
ByVal datTime As Date, _
Optional ByVal strSeparator As String = ":") _
As String
' Returns count of days, hours and minutes of datTime
' converted to hours and minutes as a formatted string
' with an optional choice of time separator.
'
' Example:
' datTime: #10:03# + #20:01#
' returns: 30:04
'
' 2005-02-05. Cactus Data ApS, CPH.
Dim strHour As String
Dim strMinute As String
Dim strHourMinute As String
strHour = CStr(Fix(datTime) * 24 + Hour(datTime))
' Add leading zero to minute count when needed.
strMinute = Right("0" & CStr(Minute(datTime)), 2)
strHourMinute = strHour & strSeparator & strMinute
FormatHourMinute = strHourMinute
End Function
and this expression as ControlSource for your textbox:
=FormatHourMinute([EndingTime]-[BeginningTime])
However (see comments) this simple expression is only valid for dates of positive numeric value which are dates after 1899-12-30.
To cover all dates, you will need a proper method for calculating a timespan, and that can be done using this function:
' Converts a date value to a timespan value.
' Useful only for date values prior to 1899-12-30 as
' these have a negative numeric value.
'
' 2015-12-15. Gustav Brock, Cactus Data ApS, CPH.
'
Public Function DateToTimespan( _
ByVal Value As Date) _
As Date
ConvDateToTimespan Value
DateToTimespan = Value
End Function
' Converts a date value by reference to a linear timespan value.
' Example:
'
' Date Time Timespan Date
' 19000101 0000 2 2
'
' 18991231 1800 1,75 1,75
' 18991231 1200 1,5 1,5
' 18991231 0600 1,25 1,25
' 18991231 0000 1 1
'
' 18991230 1800 0,75 0,75
' 18991230 1200 0,5 0,5
' 18991230 0600 0,25 0,25
' 18991230 0000 0 0
'
' 18991229 1800 -0,25 -1,75
' 18991229 1200 -0,5 -1,5
' 18991229 0600 -0,75 -1,25
' 18991229 0000 -1 -1
'
' 18991228 1800 -1,25 -2,75
' 18991228 1200 -1,5 -2,5
' 18991228 0600 -1,75 -2,25
' 18991228 0000 -2 -2
'
' 2015-12-15. Gustav Brock, Cactus Data ApS, CPH.
'
Public Sub ConvDateToTimespan( _
ByRef Value As Date)
Dim DatePart As Double
Dim TimePart As Double
If Value < 0 Then
' Get date (integer) part of Value shifted one day
' if a time part is present as -Int() rounds up.
DatePart = -Int(-Value)
' Retrieve and reverse time (decimal) part.
TimePart = DatePart - Value
' Assemble date and time part to return a timespan value.
Value = CDate(DatePart + TimePart)
Else
' Positive date values are identical to timespan values by design.
End If
End Sub
Then your expression will look like:
=FormatHourMinute(DateToTimespan([EndingTime])-DateToTimespan([BeginningTime]))
which for Gord's example values, #1899-12-28 01:00:00# and #1899-12-27 23:00:00#, will return 2:00.

adding current date as a parameter to a query in clover ETL

I have a query block for retrieving data from MSSQL Server. the query has some hardcoded date values which needs to be changed everyday to import the daily feed. I need to automate this execution. I am using cloverETL for executing the query right now.
Here is the query (its a query to retrieve sharepoint activity data)
use
DocAve_AuditDB;
DECLARE
#ParameterValue VARCHAR(100),
#SQL
VARCHAR(MAX)
SET
#SQL = STUFF((SELECT 'UNION ALL SELECT COL_ItemTypeName, COL_UserName, COL_MachineIp, COL_DocLocation, DATEADD(SECOND, COL_Occurred / 1000, ''19700101 00:00'') as Date_Occurred, COL_EventAction FROM '+ TABLE_NAME + ' WHERE DATEADD(SECOND, COL_Occurred / 1000, ''19700101 00:00'') BETWEEN '+ '''20120515'''+ 'AND' + '''20120516'''+ 'AND ' + 'COL_ItemTypeName='+ '''Document''' AS 'data()'
FROM INFORMATION_SCHEMA.TABLES
WHERE
TABLE_NAME LIKE '%2012_05%'
FOR
XML PATH('')),1,10,'')
EXEC
(#SQL)
In the above block I want the TABLE_NAME LIKE param i.e. %2012_05% to be a variable retrieved from the current data and also the date values in the between clause
BETWEEN '+ '''20120515'''+ 'AND' + '''20120516'''
to be todays date-1 and todays date
should create a small java program for handling this or it can be done directly in the query itself? if yes how?
Thanks in Advance
Use GETDATE() or CURRENT_TIMESTAMP to obtain the current date (and time).
Use CONVERT() with the 112 format specifier to convert the current timestamp to a string formatted as YYYYMMDD.
Use DATEADD() for calculations (like subtracting one day) on dates/times.
Use SUBSTRING() to subtract parts from the formatted date string to rearrange them to the %YYYY_MM% format.
Or you can use inline ctl notation in DBInputTable:
SELECT 'UNION ALL SELECT COL_ItemTypeName, COL_UserName, COL_MachineIp, COL_DocLocation, DATEADD(SECOND, COL_Occurred / 1000, ''19700101 00:00'') as Date_Occurred, COL_EventAction FROM `date2str(today(), "yyyy_MM")` WHERE DATEADD(SECOND, COL_Occurred / 1000, ''19700101 00:00'') BETWEEN '+ '''`date2str(today(), "yyyyMMdd")`'''+ 'AND' + '''`date2str(dateAdd(today(),1,day), "yyyyMMdd")`'''+ 'AND ' + 'COL_ItemTypeName='+ '''Document''' AS 'data()'