473,748 Members | 10,771 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to reset AutoNumber sequence?

Is there a way to reset the AutoNumber sequence?

I have several tables that use the AutoNumber field as the Primary Key, and
I'd like to somehow do an Import/Export that will make remove the breaks in
the sequence. A few breaks in sequence is not a big deal, but I have one
table with under 200 records, but the last AutoNumber PK ID field is over
1500 - due to a lot of edits....
Nov 12 '05 #1
12 23773
DFS
deko,

* create new tables and import all fields except the AutoNumber -
problematic if you have parent/child relationships.

* drop the AutoNumber field, save the table, repair and compact the database
(just because), and add back an AutoNumber field - again, problematic if you
have parent/child relationships.

Recommendation (not being sarcastic): don't get hung up on sequential
AutoNumbers, or small AutoNumbers, or AutoNumbers matching the number of
records in the table. I have SQL Server tables with 8-digit AutoNumbers
(IDENTITYs in SQL).

Your pk fields aren't used for Account Numbers, Invoice Numbers, etc.,
right? So it's just a unique number, and small - let it be.

"deko" <dj****@hotmail .com> wrote in message
news:BC******** ***@newssvr29.n ews.prodigy.com ...
Is there a way to reset the AutoNumber sequence?

I have several tables that use the AutoNumber field as the Primary Key, and I'd like to somehow do an Import/Export that will make remove the breaks in the sequence. A few breaks in sequence is not a big deal, but I have one
table with under 200 records, but the last AutoNumber PK ID field is over
1500 - due to a lot of edits....

Nov 12 '05 #2
> Your pk fields aren't used for Account Numbers, Invoice Numbers, etc.,
right? So it's just a unique number, and small - let it be.


The ID numbers are visible to the user and can be used for searching, but
sequence is not really important. I don't expect the Entity table to exceed
100,000 records, and a 4 or 5 digit Entity_ID is just fine. But I'd like
the "Help" entry to be Entity_ID 1 - it would be nice to purge the test data
and insert the Help entry as the first record.

Perhaps I could create a blank database, import just the table structures,
then drop the ID fields on the original database, and import just the data -
would this re-order all the AutoNumber fields? How can I import the table
data without the structures?

Could I use this code instead of Auto Number? Or is this needless overhead?

Private Sub Form_BeforeInse rt(Cancel As Integer)

Dim db As DAO.Database
Dim rst As DAO.Recordset
Set db = CurrentDb
Set rst = db.OpenRecordse t("Select max(Entity_ID) as imax from
tblEntity")
rst.MoveFirst
Me!Entity_ID = rst!imax + 1
rst.Close
Set db = Nothing
Set rst = nothing

End Sub
Nov 12 '05 #3
On Tue, 13 Jan 2004 06:17:24 GMT in comp.databases. ms-access, "deko"
<dj****@hotmail .com> wrote:
Your pk fields aren't used for Account Numbers, Invoice Numbers, etc.,
right? So it's just a unique number, and small - let it be.
The ID numbers are visible to the user and can be used for searching, but
sequence is not really important. I don't expect the Entity table to exceed
100,000 records, and a 4 or 5 digit Entity_ID is just fine. But I'd like
the "Help" entry to be Entity_ID 1 - it would be nice to purge the test data
and insert the Help entry as the first record.


Compacting usually resets to the highest number in the table + 1 so
compact after deleting test data.
Perhaps I could create a blank database, import just the table structures,
then drop the ID fields on the original database, and import just the data -
would this re-order all the AutoNumber fields? How can I import the table
data without the structures?
Using the import wizard, import into an existing table, or you can
link the tables from the other database and run a series of append
queries.
Could I use this code instead of Auto Number? Or is this needless overhead?

Private Sub Form_BeforeInse rt(Cancel As Integer)

Dim db As DAO.Database
Dim rst As DAO.Recordset
Set db = CurrentDb
Set rst = db.OpenRecordse t("Select max(Entity_ID) as imax from
tblEntity")
rst.MoveFirst
Me!Entity_ID = rst!imax + 1
rst.Close
Set db = Nothing
Set rst = nothing

End Sub


It's an overhead, whether it's needless is a matter of opinion, the
pros can outweigh the cons. This way you'll get no gaps (until someone
deletes a record). There's many ways of rolling your own autonumber,
from the simple DMax()+1 to the more complex of having a table full of
table names and autonumber values, the latter checking the target
table in case it already exists and adding another 1, etc, which would
mean you could reset to 1 and re-use any gaps left by deletion.

However I wouldn't do this as early as Form_BeforeInse rt() as you'll
duplicate the number as soon as two people enter a record at the same
time. Perhaps in Form_BeforeUpda te() and check to see if on a new
record or that the ID is null first.

--
A)bort, R)etry, I)nfluence with large hammer.
Nov 12 '05 #4
> Using the import wizard, import into an existing table, or you can
link the tables from the other database and run a series of append
queries.


I think that's the ticket...

* create new.mdb
* import all objects, definition only
* link to tables in orig.mdb
* run a series of append queries

I'm going to try to gin this up in vba (everything after create new.mdb)

Should I use the CreateWorkspace method? What are Workspaces, anyway?
Can I use DoCmd.TransferD atabase and loop through each Form, Query, Report,
Module and Table? How to get list of objects from orig.mdb?
I think I can figure out how to link all the tables, and setting up the
append queries shouldn't be too difficult.

Here's some pseudo code as a first draft - suggestions welcome!

'[standard module in new.mdb]
Public Sub ImportLinkAppen d()

' import all the objects from orig.mdb
For Each Table In tbldefs '<<== how to programatically get list of
tables in orig.mdb?
DoCmd.TransferD atabase acImportworkspa ce, "Microsoft Access",
"C:\orig.md b", acTable, varOrigTableNam e, varNewTableName , True
Next

' For Each Form In ...
'
' For Each Query In ...
'
' For Each Report In ...
'
' For Each Module In ...
' link to the tables in orig.mdb
Set tdf = db.CreateTableD ef(varTbl)
strLink = "Access 11;DATABASE=C:\ orig.mdb"
tdf.Connect = strLink
tdf.SourceTable Name = "varTbl"
db.TableDefs.Ap pend tdf '<<== will this cause problems since the table
names will be the same?

' run append queries
DoCmd.RunSQL "INSERT INTO varNewTableName SELECT varOldTableName .* FROM
varOldTableName "

End Sub
Nov 12 '05 #5
Here's another hack at it.....

Private Sub ImportObjects()
Dim wrkJet As DAO.Workspace
Dim con As DAO.Container
Dim db As DAO.Database
Dim doc As DAO.Document
Dim varName, varContainer As Variant
Set wrkJet = CreateWorkspace ("", "admin", "", dbUseJet)
Set db = wrkJet.OpenData base("C:\orig.m db", True)
For Each varContainer In Array("Tables", "Forms", "Reports", "Modules",
"Queries")
Set con = db.Containers(v arContainer)
For Each doc In con.Documents
Select Case doc.Name ???
Case "Tables"
DoCmd.TransferD atabase acImport, "Microsoft Access",
"C:\orig.md b", acTable, varName, varName, True
Case "Queries"
Case etc...
End Select
Next
Next
End Sub

+++++++++++++++ +++++

If I do succeed in importing all the objects this way, will the table
relationships be preserved? If I go to File >> Get External Data >> Import,
and select orig.mdb, the "Import Objects" window appears with a check box
for Importing Relationships - how do I specify this in code? The assumption
here is that I can emulate the functionality of that Import Objects window
with code... what about hidden and system objects???
Nov 12 '05 #6
When I run code to inventory my database, I get some "Queries" that look
like this:

~sq_ffrmTxImpor t

I also get all the normal looking queries, like:

qry100

Does the "~" mean it's some kind of temp object?

Below is complete code of how I get inventory

Option Compare Database
Option Explicit
Private Sub AddInventory(st rContainer As String)
Dim con As DAO.Container
Dim db1, db2 As DAO.Database
Dim doc As DAO.Document
Dim rst As DAO.Recordset
Dim intI As Integer
Dim strType As String
Dim varRetval As Variant
Dim wrkJet As DAO.Workspace
Set wrkJet = CreateWorkspace ("", "admin", "", dbUseJet)
Set db2 = wrkJet.OpenData base("C:\orig.m db", True)
Set db1 = CurrentDb
Set rst = db1.OpenRecords et("tblInventor y")
Set con = db2.Containers( strContainer)
For Each doc In con.Documents
If Not isTemp(doc.Name ) Then
If strContainer = "Tables" Then
strType = IIf(isTable(doc .Name), "Tables", "Queries")
Else
strType = strContainer
End If
With rst
.AddNew
!Container = strType
!Owner = doc.Owner
!Name = doc.Name
!DateCreated = doc.DateCreated
!LastUpdated = doc.LastUpdated
.Update
End With
End If
Next doc
End Sub
Private Sub CreateInventory ()
If (CreateTable()) Then
Call AddInventory("T ables")
Call AddInventory("F orms")
Call AddInventory("R eports")
Call AddInventory("S cripts")
Call AddInventory("M odules")
Call AddInventory("R elationships")
Else
MsgBox "Unable to create tblInventory."
End If
End Sub
Private Function CreateTable() As Boolean
On Error GoTo HandleErr
Dim qdf As DAO.QueryDef
Dim db As DAO.Database
Dim strSql As String
Set db = CurrentDb()
db.Execute "Drop Table tblInventory"
strSql = "CREATE TABLE tblInventory (Name Text (255), " & _
"Container Text (50), DateCreated DateTime, " & _
"LastUpdate d DateTime, Owner Text (50), " & _
"ID AutoIncrement Constraint PrimaryKey PRIMARY KEY)"
db.Execute strSql
db.TableDefs.Re fresh
CreateTable = True
Exit_Here:
Exit Function
HandleErr:
Select Case Err.Number
Case 3376, 3011 ' Table or Object not found
Resume Next
Case Else
CreateTable = False
End Select
Resume Exit_Here
End Function
Private Function isTable(ByVal strName As String)
On Error Resume Next
Dim tdf As DAO.TableDef
Dim db As DAO.Database
Dim wrkJet As DAO.Workspace
Set wrkJet = CreateWorkspace ("", "admin", "", dbUseJet)
Set db = wrkJet.OpenData base("C:\orig.m db", True)
Set tdf = db.TableDefs(st rName)
isTable = (Err = 0)
On Error GoTo 0
End Function
Private Function isTemp(ByVal strName As String)
isTemp = Left(strName, 7) = "~TMPCLP"
End Function
Private Sub cmdCreateInvent ory_Click()
On Error Resume Next
Me!frmInventory Datasheet.Form. RecordSource = ""
Call CreateInventory
Me!frmInventory Datasheet.Form. RecordSource = "tblInvento ry"
Me!lblObjCount. Caption = DCount("Name", "tblInvento ry") & " Objects"
End Sub
Private Sub Form_Open(Cance l As Integer)
Me!frmInventory Datasheet.Form. RecordSource = ""
End Sub
Nov 12 '05 #7
They are temp queries, designed to improve performance when forms/reports
are based on SQL statements.
--
MichKa [MS]
NLS Collation/Locale/Keyboard Development
Globalization Infrastructure and Font Technologies

This posting is provided "AS IS" with
no warranties, and confers no rights.
"deko" <dj****@hotmail .com> wrote in message
news:fl******** *******@newssvr 29.news.prodigy .com...
When I run code to inventory my database, I get some "Queries" that look
like this:

~sq_ffrmTxImpor t

I also get all the normal looking queries, like:

qry100

Does the "~" mean it's some kind of temp object?

Below is complete code of how I get inventory

Option Compare Database
Option Explicit
Private Sub AddInventory(st rContainer As String)
Dim con As DAO.Container
Dim db1, db2 As DAO.Database
Dim doc As DAO.Document
Dim rst As DAO.Recordset
Dim intI As Integer
Dim strType As String
Dim varRetval As Variant
Dim wrkJet As DAO.Workspace
Set wrkJet = CreateWorkspace ("", "admin", "", dbUseJet)
Set db2 = wrkJet.OpenData base("C:\orig.m db", True)
Set db1 = CurrentDb
Set rst = db1.OpenRecords et("tblInventor y")
Set con = db2.Containers( strContainer)
For Each doc In con.Documents
If Not isTemp(doc.Name ) Then
If strContainer = "Tables" Then
strType = IIf(isTable(doc .Name), "Tables", "Queries")
Else
strType = strContainer
End If
With rst
.AddNew
!Container = strType
!Owner = doc.Owner
!Name = doc.Name
!DateCreated = doc.DateCreated
!LastUpdated = doc.LastUpdated
.Update
End With
End If
Next doc
End Sub
Private Sub CreateInventory ()
If (CreateTable()) Then
Call AddInventory("T ables")
Call AddInventory("F orms")
Call AddInventory("R eports")
Call AddInventory("S cripts")
Call AddInventory("M odules")
Call AddInventory("R elationships")
Else
MsgBox "Unable to create tblInventory."
End If
End Sub
Private Function CreateTable() As Boolean
On Error GoTo HandleErr
Dim qdf As DAO.QueryDef
Dim db As DAO.Database
Dim strSql As String
Set db = CurrentDb()
db.Execute "Drop Table tblInventory"
strSql = "CREATE TABLE tblInventory (Name Text (255), " & _
"Container Text (50), DateCreated DateTime, " & _
"LastUpdate d DateTime, Owner Text (50), " & _
"ID AutoIncrement Constraint PrimaryKey PRIMARY KEY)"
db.Execute strSql
db.TableDefs.Re fresh
CreateTable = True
Exit_Here:
Exit Function
HandleErr:
Select Case Err.Number
Case 3376, 3011 ' Table or Object not found
Resume Next
Case Else
CreateTable = False
End Select
Resume Exit_Here
End Function
Private Function isTable(ByVal strName As String)
On Error Resume Next
Dim tdf As DAO.TableDef
Dim db As DAO.Database
Dim wrkJet As DAO.Workspace
Set wrkJet = CreateWorkspace ("", "admin", "", dbUseJet)
Set db = wrkJet.OpenData base("C:\orig.m db", True)
Set tdf = db.TableDefs(st rName)
isTable = (Err = 0)
On Error GoTo 0
End Function
Private Function isTemp(ByVal strName As String)
isTemp = Left(strName, 7) = "~TMPCLP"
End Function
Private Sub cmdCreateInvent ory_Click()
On Error Resume Next
Me!frmInventory Datasheet.Form. RecordSource = ""
Call CreateInventory
Me!frmInventory Datasheet.Form. RecordSource = "tblInvento ry"
Me!lblObjCount. Caption = DCount("Name", "tblInvento ry") & " Objects"
End Sub
Private Sub Form_Open(Cance l As Integer)
Me!frmInventory Datasheet.Form. RecordSource = ""
End Sub

Nov 12 '05 #8
> They are temp queries, designed to improve performance when forms/reports
are based on SQL statements.


10-4 ... thx for the clarification

As for AutoNumber re-sequencing, the plan is:

* create new.mdb
* import all objects, definition only
* link to tables in orig.mdb
* run a series of append queries

I'm not sure using code for the object imports is such a great idea... still
working on that (could just do it manually) - but this code should pull the
data from orig.mdb after I've imported the table definitions (into new.mdb)
and deleted the AutoNumber columns from the tables in orig.mdb. This should
re-sequence the AutoNumber IDs, removing any breaks in sequence. Again, any
suggestion for improvement welcome...
Private Sub GetData()

Dim db, dbs As DAO.Database
Dim obj As Object
Dim strPath As String
Dim wrkJet As DAO.Workspace
Set wrkJet = CreateWorkspace ("", "admin", "", dbUseJet)
Set db = wrkJet.OpenData base("C:\orig.m db", True)
Set dbs = CurrentDb
strPath = "C:\orig.md b"
For Each obj In db.TableDefs
If Left(obj.Name, 2) <> "MS" And Left(obj.Name, 1) <> "~" Then
DoCmd.TransferD atabase acLink, "Microsoft Access", strPath,
acTable, obj.Name, obj.Name & "_orig"
'Debug.Print obj.Name & " connected"
DoCmd.SetWarnin gs False
DoCmd.RunSQL ("INSERT INTO " & obj.Name & " SELECT " & obj.Name
& "_orig.* FROM " & obj.Name & "_orig")
DoCmd.SetWarnin gs True
dbs.Execute "DROP TABLE " & obj.Name
End If
Next

End Sub
Nov 12 '05 #9
On Tue, 13 Jan 2004 17:44:06 GMT in comp.databases. ms-access, "deko"
<dj****@hotmail .com> wrote:
If Left(obj.Name, 2) <> "MS" And Left(obj.Name, 1) <> "~" Then
You may be wiser to your naming conventions than I but I think you
should exclude "MSys*" rather than just "MS*"
DoCmd.SetWarnin gs False
DoCmd.RunSQL ("INSERT INTO " & obj.Name & " SELECT " & obj.Name
& "_orig.* FROM " & obj.Name & "_orig")
DoCmd.SetWarnin gs True
dbs.Execute "DROP TABLE " & obj.Name


While it may be nice to have the percentage complete provided by the
DoCmd, it also requires you turn warnings off as you have in the code
above. You must make sure you turn it on again if any error occurs
that prevents the next line running. Also it will suppress some lesser
(but no means less important) errors. It is also the slowest method of
running a query, better to use

dbs.Execute "insert into...", dbFailOnError

to catch any errors that do occur, although copying to the same
structure of table, none should occur but then if it was always that
easy then people wouldn't pay me to do it :-)

--
A)bort, R)etry, I)nfluence with large hammer.
Nov 12 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
2871
by: Charles Robinson III | last post by:
The AutoNumber sequence in my database is currently formatted as '000000'. When a new record is created, the AutoNumber would go from 000001, 000002, 000003 and so on. I want to track via AutoNumber the year each record was created. Basically, if a record was entered in 2003, the AutoNumber would look something like 03-000001 and then 03-000002, and so on. When a record would be entered in 2004, the AutoNumber would look something...
3
8674
by: Cillies | last post by:
Hello, I was wondering if anyone knew how to reset an auto number. I.E. in my database I have two tables with autonumbers as primary keys. So I was wondering if anyone knew an easy way of resetting them, as I have made a few errors throughout the database. Kindest Regards
2
5618
by: N. Graves | last post by:
Hey is there a command like in SQL Transactional that will reset the Autonumber field to the highest number in the found in the field? I developing a access database with a several table that have autonumbering. I would like to reset them back to 0 after I delete all the rows of data. Is there an easier way to do this other than creating a new field and remove the old autonumber? Maybe in the system table?
16
20523
by: John Baker | last post by:
Hi: I know this is a strange question, but I have inherited a system where files are copied and records re auto numbered (as an index field) )frequently, and I am wondering how high the number can go without the system crashing. An ancillary question is how one resets an auto number so that the sequence starts again at 1. In the case of this file, the auto number field serves no useful purpose except as an
4
8790
by: Danny | last post by:
I have a db that has a table that is never deleted but just has records cleaned out "delete * from table" but each time it is populated, the autonumber is not reset to 0 and picks up where it left off even though I delete the records. Is there a way in code i can compact the database (I know this is the way to reset that blank tables autonumber to 0). I know I can compacdt on exit but
4
2116
by: Vladislav | last post by:
My customers have reported strange behaviour of the locally used modules for running the register on stroke patients, specifically, adding new patient to the register. When analising a sample, I have found that an autonumber variable (id) doesn't behave as expected. At some instant after the record with id=180, the next record is coming with id=158. I can't find any reasonable explanation. Could anybody? V.M.
4
3343
by: dhcomcast | last post by:
We're starting to use Oracle for the back-end instead of a separate Access .mdb file for the data and everything as gone surprisingly well so far. We are learning Oracle as we go; Yikes! But we have very patient DBA's at the main office to answer newbie questions. Using Access 2002 with linked ODBC tables to Oracle 9 (9i? not sure), ODBC driver is SQORA32.DLL, verson 9.02.00.00. My "Error 3167: Record is deleted" comes when I use...
3
11241
by: trueblue7 | last post by:
I apologize if this question has been asked before... I'm trying to reset autonumber fields back to 1. The autonumber fields are part of the composite primary keys. I followed the MS help with a temp table and append query. I can change the number to anything but 1. I'm using Access XP and saving as 2000. Any help is appreciated.
2
2821
mkremkow
by: mkremkow | last post by:
Access 2003 on XP Someone here at work deleted a record (&$%^&*&!!!) and screwed up the Autonumber "Job ID" field . I need to reset the Autonumber field back to it's original numbers and still keep all the data in the table assigned to the correct Job ID (1-155). I copied everything from the table to Excel for safekeeping. I deleted the Autonumber field and went through the steps (http://support.microsoft.com/kb/812718 ) but when I...
0
8989
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9537
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9367
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9243
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6795
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6073
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4599
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
2780
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2213
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.