Sequential Numbers Automatically Populate a field - sql

I have an Access database that we use to house Worker's Compensation Accident Information. One of the required fields is an OSHA recordable number that is sequential starting with "01" and the two digit year of the accident (ex. 01-14).
I need to be able to programmitically look into my table see what numbers have already been used and find the next number in the sequence. It also needs to reset to 1 at the beginning of a new year.
Example:
table reads
01-14
02-14
03-14
The new number that populates the textbox should be 04-14
Help!

Given that you have a multi-user database, see insert query with sequential primary key or Access VBA: Find max number in column and add 1 for code to get the next sequential number.
You can use Year and the seed number to create the next OSHA number. You can reset the seed number on year change.
DMax is a possibility, but I strongly suggest you do not use it in a multi-user database.

From what you have described, it sounds like the OSHA number should be generated as and when needed instead of being assigned and stored when the table row is created. My suggestion would be to just have the primary key (accident_id) be an autoincremented long integer, the standard practice in Access. And also you need an accident_date column to be a datetime or similar. Or at the very least an accident_year column. Then when you need an OSHA number (say in a report), just have some VBA to generate it using the primary key--accident_id--and the accident_date or accident_year column. You will be taking advantage of the fact that Access autoincremented primary keys are never re-used--even when their rows are deleted, those numbers are never recycled to be used in other rows. So given a long integer primary key, and a date, you can always reproduce the exact same OSHA number, with a simple algorithm something like the following:
function osha_number(accident_id as long) as string
accident_year = ... ' get (last two digits of) accident year from accidents table using ID
year_first_accident_id = ... ' get ID of first accident of this year
year_this_accident_num = accident_id - year_first_accident_id + 1
osha_number = year_this_accident_num & "-" & accident_year
end function

Related

Custom number in MS Access

Am a newbie in Microsoft Access 2016 making a database system for processing loans.
I have made two fields:
ID e.g: 001 with datatype number and
NRC (This is the official National Registration Card number in my country e.g: "123456/78/1" )
I now want to generate a new field:
LoanNumber from the fields 1. ID and 2. NRC mentioned above.
From the examples above, I want this new field to be composed with two parts concatenated together; that is "ID-first part of NRC before the first '/' ".
e.g: LoanNumber : 001-123456
What code in the expression builder will will help me achieve this?
A number datatype value cannot be saved with preceding zeros. Use Format function to manipulate number. This can be done in a query or textbox but not in table because Format function is not available for Calculated field type.
Format([ID], "000-") & Left([NRC], 6)

Selecting data from two different tables

I have 2 tables.
Table TSTRSN
[P]Client
[P]Year
[P]Rule_Nbr
Type_Code
Table TSTOCK
[P]Client
[P]Year
TimeStamp
EndOfFiscalYear
( [P] means Primary Key)
The request is twofold:
1) List a count of all the Rule_Nbr within a given time (from TimeStamp).
...then User chooses a specific Rule_Nbr...
2) List all Client, Year, EndOfFiscalYear for that specific Rule_Nbr
So for Part 1) I have to take the Rule_Nbr, take the matching Client and Year - use that to search for the TimeStamp. If it falls within the right time, increment count by 1... and so on.
Then for Part 2) I could either have saved the data from part 1 (I don't know if this is feasible given the size of the tables) or redo the query 1) for just one Rule_Nbr.
Im very new to SQL/DB2... so how to go about doing this? My first thought was make an array, store TSTRSN.Client/Year/Rule_Nbr and then prune it by comparing it to TSTOCK.Client/Year/Timestamp but I wonder if theres a better way (Im not even sure if Arrays exist in DB2!)
Any tips?
What you're looking for is the JOIN keyword.
http://www.gatebase.toucansurf.com/db2examples13.html

Tag new records with number 1 to 6, evenly allocated

I am bringing over a record set that needs to be divided into 6 lists. I am using the field WrkList to hold the list number that will range from 1-6. I don't want to manually add the numbers to each of the new records with a repeating squence of (1, 2, 3, 4, 5, 6) as they are brought in. The WrkList field allows the records to be worked by 6 employees using queries that use the field as the criteria for that query. In any given day, over 1200 records may be appended to the table throughout the day and would need to have the WrkList field updated. I want these divided out as evenly as possible among the 6 groups as each new set of records are appended. Any help on getting started would be greatly appreciated.
Basically, you will open a recordset in DAO that includes all the records for which WrkList is Null. You will sort this by the order they came in, or some other logical criteria - whatever helps your workers have a coherent work queue (perhaps no order at all).
You will go through the recordset from beginning to end and update the WrkList field with a variable, byteWrkList.
This variable will have a value that changes with each edit. It will increment up by one, or if it was 6 for the last edit, it will return to 1.
NOTE: This code does not specify that you have filtered for Null! OpenRecordset must be based on a query that does filter for Null! (Or it must be based on a SQL string that does the same thing.)
Option Compare Database
Option Explicit
Private Sub AllocateTasks()
Public byteMax As Byte, byteWrkList as Byte
byteMax = 6
byteWrkList = 1
Dim rstTask As Recordset
Set rstTask = CurrentDb.OpenRecordset("tableOfTasks")
Do Until rstTask.EOF
if byteWrkList > byteMax then
byteWrkList = 1
else
byteWrkList = byteWrkList + 1
end if
rstTask.Edit
' Make sure you are not over-writing an existing value!
' Make sure it is NULL, or that your recordset excluded NULLs.
rstTask!WrkList = byteWrkList
rstTask.Update
rstTask.MoveNext
Loop
rstTask.Close
Set rstTask = Nothing
End Sub
Then you just need a way to invoke (trigger) the above code ... but your post doesn't really have enough information to suggest what that is.
There are alternate (and elegant) methods to obtain byteWrkList, such as using the mod() function applied to an autonumber index. (This is not important. I just had to get it off my chest because mod() is fun.) Indeed, there are alternate methods to handle this entirely; but this is what I would start with.

QlikView Set Analysis: use either column number or other unique info from row

I am trying to use Set Analysis in the table below for the column labelled test. I am trying to get sum([Best Dollar]) for the date range specified by the Start and End columns.
This expression returns results, but it's naturally static for each row of the table:
=sum({$<AsAtDate={">=40959 and <=40960"}>} [Best Dollar])/1000
This is what I want to have but it returns 0:
=Sum({$<AsAtDate={">=(num(floor(BroadcastWeekStart2))) and <=(num(floor(BroadcastWeekStart2)))+6"}>} [Best Dollar])/1000
To obtain unique start date serial numbers for each line for the start column (BroadcastWeekStart2) I use the following expression:
=(num(floor(BroadcastWeekStart2)))
How can I specify that the values or calculations used for the start and end columns are used in Set Analysis for the field above?
There is at least one information missing in your question.
Do you want to select on fixed values or should the sum depend on the current time?
For the static version something like
=sum( {$<BroadcastWeekStart2={"40959"}, BroadcastWeekStart2={"<=40960"}>} [Best Dollar])/1000
should work. (Assuming that BroadcastWeekStart2 contains these kind of values.)
Let me show you an example how I calculate values for the current week:
='Count: ' & count({$<start_week={"$(=WeekStart(Today()))"}>} Games)
where the start_week is set in the load script by:
WeekStart(date#(#4, 'YYYYMMDD')) as start_week,

Copying a record without Primary Key Constriant Error

I have found the way to copy the record that I would like, but now I am having a violation of the Primary Key constraint. Here is what I am trying to do:
We make a product that comes out of our maching into 2000 lbs bags and it is giving a number, e.g. 26273.
We store and sell it in those bags, but we also can sell it in smaller 50 lbs and 25 lbs bags.
When we convert the bag from 2000 lbs to 25 lbs the product takes up 80 bags.
Only 40 bags can be put onto a pallet, making the product number 26273 take up two pallets.
The problem we have is when we store the pallet we scan the barcode of the product and then scan the barcode of the warehouse location, ONE pallet per location, and only ONE location per pallet. If we have two pallets with the same number than we cannot store them in the warehouse.
To solve this problem my bosses what the first pallet to be number 26273B1 and the second pallet to be 26273B2 so that the pallets still contain the original number but is slighlty different in order to store them.
When the product receives a number it also goes through several tests and that data is part of the record so both of the records still nedd to contain those test results.
When I try to copy the record and place the B2 onto the number I get a Primary Key Constraint ODBC Failure. I know why I am getting the error, and I don't what to dissable the constraint to allow duplicate records, but I still need to have the ability to create this new record when we convert to 25lbs bags.
So my question: Is there any way to copy a record, slighty change the Primary Key while copying it, and still be able to save it without the Primary Key Constraint error occuring?
NOTE: the database is in SQL with the interface front-end is in Access 2007.
Why not store the original 2000 bag with the PK "26273-00-0000". That "00-0000" suffix indicates the original Bag.
For each subdivision into a smaller bag, "one-up" or increment the sequence that is suffixed at the end. You could use "00" for palletts, and "0000" for the bag-sequence number.
Hence "26273-B1-0001" - thru "26273-B1-0040" indicates the Product id that went into Pallett - one - the first 40 bags.
I am not sure how you are wanting to copy a record i.e. in a form or programatically.
Note you can have a Primary Key based on more than 1 column so provided the 2 columns together are unique then you will not violate the constraint.
Simply build what is called an append query. You can pull all of the old previous values and substitute a value for any of the columns to be something of your choice.
So, the code + sql would look like:
Dim strSql As String
Dim oldPK As String
Dim newPK As String
oldPK = "26273B1"
newPK = "26273B2"
strSql = "insert into tblPallets (PalletNumber, Description, StockNumber)" & _
"select '" & newPK & "', Description, StockNumber" & _
"from tblPallets where PallentNumber = '" & oldPK & "'"
CurrentDb.Execute strSql, dbFailOnError