473,412 Members | 2,239 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,412 software developers and data experts.

How to generate a text string for use as primary key?

Using Access 2007

My table (TblPtDemographics) contains a primary key of PtID, which is a numeric field.

Linked to this table is TblKneeSurgeryInfo, which contains a primary of SxKneeID, which is a text field. It also has a field SxKneeSide, which designates "Right" or "Left."

The format of SxKneeID should be as follows:

R111111S1

1. Where "R" indicates that the right knee was operated on (as found in SxKneeSide)
2. "111111" is the value in PtID
3. "S" is a constant indicating surgery
4. "1" indicates the first surgery the person has had on the right knee.

My main question is: How can I set up the code that would automatically generate a string to put in the SxKneeID field? I need to trim the "Right" and "Left" values down to the first letter and have access sort of autonumber the last portion of the string (for instance, if "R111111S1" already exists, use "R111111S2" when creating a new record).
I know how to get the PtID field and "S" into the string, but as for the other part--- I'm not sure how to set this up using VBA. Any help would be appreciated!
Dec 11 '10 #1

✓ answered by NeoPa

JenniferM:
Anyways, my initial approach to this problem was to perform a count of all records where PtID and SxAffectedSide (Right/Left) matched--- then add 1.
That's almost right Jennifer.

Instead of finding a count of the matching PKs though, find the Max of them and add one to that. This will ensure none is ever reused and any new ones added are greater than all existing ones.

Let me know if this is enough for you or if you need the DMax() code illustrated for you. The code for this should fit on a single line and can be done from within SQL too if necessary.

10 2473
NeoPa
32,556 Expert Mod 16PB
Show us what you've got Jennifer. If we see your code we know you've already looked at it for yourself first, and we can see how much you do and don't understand - how much you need.

PS. Is the numeric value (111111 in your example) a fixed number of digits, or does it depend on the number? I strongly suggest you decide to use a fixed number of digits going forward even if you hadn't considered it before now.
Dec 12 '10 #2
PtID is a numeric value that will vary between 5-7 digits in length (I wish they were all one length, but these are the chart numbers that I have no control over--- dang it!).

Anyways, my initial approach to this problem was to perform a count of all records where PtID and SxAffectedSide (Right/Left) matched--- then add 1.

Here's my code (I realize there's probably a cleaner way of doing this, but you get the general idea):

Expand|Select|Wrap|Line Numbers
  1. Dim db As DAO.Database
  2. Set db = CurrentDb
  3.  
  4. Dim strIDPrefix As String
  5. Dim strSide As String
  6. Dim strSxNumber As String
  7. Dim strSxKneeID As String
  8.  
  9. Dim strSQL As String
  10.  
  11. If [SxAffectedKnee] = "Right" Then
  12.     strSide = "R"
  13.     Else
  14.     strSide = "L"
  15.     End If
  16.  
  17. strIDPrefix = strSide & [Forms]![FrmPatientDemographics]![PtID] & "S"
  18.  
  19. strNumber = DCount("*", "TblSurgeryForm", "[TblSurgeryForm].[PtID] = " & _
  20. [Forms]![FrmPatientDemographics]![PtID] & _
  21. " AND [TblSurgeryForm].[SxAffectedKnee] = " _
  22. & Chr(34) & Me.SxAffectedKnee & Chr(34) & _
  23. " AND [TblSurgeryForm].[SxID] <> " & Me.SxID) + 1
  24.  
  25. If strNumber = "1" Then
  26.     strSxKneeID = Left(strIDPrefix + strNumber, Len(strIDPrefix + strNumber) - 1)
  27.     Else
  28.     strSxKneeID = strIDPrefix + strNumber
  29.     End If
  30.  
  31. strSQL = "UPDATE [TblSurgeryForm] " _
  32.        & "SET [SxKneeID] = " & Chr(34) & strSxKneeID & Chr(34) _
  33.        & " WHERE ([SxID] = " & Me.SxID & ")"         
  34.  
  35. Call db.Execute(strSQL)



Now, this works fine assuming no surgery records are deleted. There will be a problem with my approach if, say for instance:

A patient (PtID = 55555) has three surgeries on the right knee which will be:
R55555S
R55555S2
R55555S3

If I delete the record for either of the first two, my DCount function approach will generate the next string to be R55555S3, which already exists. I don't know if I'm explaining this adequately, so let me know where more clarification is needed..... Thanks!!
Jan 12 '11 #3
ADezii
8,834 Expert 8TB
Assuming existing Records are in the correct sequence:
  1. Create an [ID] Field {AUTONUMBER} in tblKneeSurgeryInfo. We'll use this Field to create the proper Sort Order so that the highest [SxKneeID] Value for a given Patient will always be the last Record in the Recordset. Sorting on [SxKneeID] itself will not work since it is a Text Field.
  2. Copy-N-Paste the following Code to wherever appropriate.
  3. Make any Table/Field/Form Field Name changes to conform to your specific needs.
    Expand|Select|Wrap|Line Numbers
    1. Dim MyDB As DAO.Database
    2. Dim rstKnee As DAO.Recordset
    3. Dim strNewKneeID As String
    4. Dim strSQL
    5.  
    6. strSQL = "SELECT * FROM tblKneeSurgeryInfo WHERE [tblKneeSurgeryInfo].[PtID] = " & _
    7.           [Forms]![FrmPatientDemographics]![PtID] & _
    8.          "AND [tblKneeSurgeryInfo].[SxKneeSide] = '" & _
    9.           [Forms]![FrmPatientDemographics]![SxAffectedKnee] & _
    10.          "' ORDER BY [tblKneeSurgeryInfo].[ID];"
    11.  
    12. Set MyDB = CurrentDb
    13. Set rstKnee = MyDB.OpenRecordset(strSQL, dbOpenSnapshot)
    14.  
    15. With rstKnee
    16.   If Not .BOF And Not .EOF Then       'Yep, we have Records!
    17.     .MoveLast       'Last Value for [SxKneeID]
    18.       strNewKneeID = Left$(![SxKneeSide], 1) & ![PtID] & "S" & _
    19.                      Val(Mid$(![SxKneeID], InStr(![SxKneeID], "S") + 1)) + 1
    20.   Else
    21.     'No Records matching Patient and Knee
    22.     strNewKneeID = Left$(![SxKneeSide], 1) & ![PtID] & "S"
    23.   End If
    24. End With
    25.  
    26. rstKnee.Close
    27. Set rstKnee = Nothing
    28.  
    29. MsgBox "Next [SxKneeID] = " & strNewKneeID
Jan 13 '11 #4
NeoPa
32,556 Expert Mod 16PB
JenniferM:
Anyways, my initial approach to this problem was to perform a count of all records where PtID and SxAffectedSide (Right/Left) matched--- then add 1.
That's almost right Jennifer.

Instead of finding a count of the matching PKs though, find the Max of them and add one to that. This will ensure none is ever reused and any new ones added are greater than all existing ones.

Let me know if this is enough for you or if you need the DMax() code illustrated for you. The code for this should fit on a single line and can be done from within SQL too if necessary.
Jan 13 '11 #5
ADezii
8,834 Expert 8TB
Hello NeoPa. As usual, I'm probably missing something but won't DMax() give erroneous results under certain conditions, such as?
Expand|Select|Wrap|Line Numbers
  1. DMax("[SxKneeID]","tblKneeSurgeryInfo", "[PtID]=55555 AND [SxKneeSide] = 'Right'")
will return
Expand|Select|Wrap|Line Numbers
  1. R55555S9
when there exists
Expand|Select|Wrap|Line Numbers
  1. R55555S10
Thanks in advance...
Jan 13 '11 #6
Thanks for the replies. After ADezii's first post, I created a numeric field within the table called SxSurgeryNumber. I ended up using SQL to get the max from this field using this code:


Expand|Select|Wrap|Line Numbers
  1. Dim rst As DAO.Recordset
  2.  
  3. Set rst = CurrentDb.OpenRecordset("SELECT _
  4.        MAX(SxSurgeryNumber) FROM [TblSurgeryForm] _
  5.        WHERE [PtID] = " & _
  6.        [Forms]![FrmPatientDemographics]![PtID] & _
  7.        " AND [SxAffectedKnee] = " & _
  8.        Chr(34) & Me.SxAffectedKnee & Chr(34))
  9.             If Not (rst.EOF And rst.BOF) Then
  10.             lngSxSurgeryNumber = Nz(rst.Fields(0), 0) + 1
  11.             End If
  12.         rst.Close
  13.         Set rst = Nothing

I then updated the SxSurgeryNumber field with the value I got here and created my string in a similar manner to my first post.... And it will work now, because all new numbers are based on the max of the field! Thanks for all the assistance, guys!!
Jan 13 '11 #7
ADezii
8,834 Expert 8TB
Nice job, JenniferM. How are you handling New Patients, manual entry?
Jan 13 '11 #8
Yes, all new patients are stored in TblPatientDemographics, with their primary key PtID.
I gather you're asking about how I handle numbering new ones--- in this case, I'm going off their chart number, which is just a random number anywhere from 5-7 digits long. I wish there was some rhyme or reason to how we get these, but there just isn't.... Ergo, I have to manually input their PtID.
Jan 13 '11 #9
ADezii
8,834 Expert 8TB
It won't be long until you are advising us!
Jan 13 '11 #10
NeoPa
32,556 Expert Mod 16PB
ADezii:
Hello NeoPa. As usual, I'm probably missing something but won't DMax() give erroneous results under certain conditions, such as?
It's a good point my friend (which frankly I hadn't gone into that much detail on without needing to). In most cases (this is an exception as the size of none of the subfields within the value is reliable so, although Left(), Right() & Mid() would work, InStr() doesn't (except in VBA), so this is not practicable within pure SQL), this could be handled by setting the Expr parameter to return a Val() of the resulting subfield rather than the simple field reference itself.

As I said, because the start position, and even the length, of this subfield are both non-predictable in the current circumstances, this couldn't be done in simple SQL. It can still work if done within VBA ok of course.
Jan 13 '11 #11

Sign in to post your reply or Sign up for a free account.

Similar topics

5
by: tmb | last post by:
I need to search a folder & sub-folders for key words in ASP files... I can open the files with Notepad and see the text string there... But when I try to navigate to the folder with Windows...
2
by: johkar | last post by:
Would there ever be any problems with the following script depending on what type of characters are in the text string? I am appending the value of hidden form field to the query string. ...
2
by: charlie_M | last post by:
I have the following code: <script type=text/javascript> function hide_tooltip(){ var hp = document.getElementById("tooltipper"); hp.style.left=0; hp.style.top=0; hp.style.width=1;...
3
by: Dixie | last post by:
I am trying to create a registration system in which a unique text string accessible in a table of the program is turned into a unique number which will be matched with a number sent to the...
2
by: UJ | last post by:
I have need to convert a text string (with formatting) to an image. This is so that I can resize the image to different sizes and the formatting stays exactly the same regardless of the size. I...
6
by: larry mckay | last post by:
Hi, Does anyone have any simple text string encryption routines that are easy to implement? I'm trying to prevent users and system administrators from figuring out how I implement things....
25
by: electrixnow | last post by:
in MS VC++ Express I need to know how to get from one comma delimited text string to many strings. from this: main_string = "onE,Two,Three , fouR,five, six " to these: string1 =...
5
by: geotso | last post by:
Here is the scenario: 1. I have a table (tblCalendar) with the following fields: caldID caldDate caldTitle caldInfo nWinW nWinH
6
by: Dennis | last post by:
Is there anything built in to vb.net that will take a plain text string and reformat it as HTML? What I mean is: o replace newlines with <BR> o replace " with &quot; o etc. I am using vb.net...
2
by: Mufasa | last post by:
Is there anyway to generate a string that contains the name of the namespace, the object name and then the function/procedure name that is currently running. I want to use this for logging...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.