Autonumber - start from ZERO - sql

So, I know how to add an autonumber field to a table using SQL:
dblocal.Data.Execute "CREATE TABLE " & TableName & " (" & FieldName & " COUNTER(1,1) )"
Where dblocal is the passed database reference with TableName & FieldName the appropriate names for the desired creation of the table.
However, I want the counter to start at ZERO not ONE. And I know it's possible because the table I need to repair / duplicate starts with ZERO
What am I not finding on the internet to aid me in this task?
My search-fu fails me.

Related

can't insert value from a form into lookup field

I have a form that insert data into a table , the problem is I can't insert value from my combo box into a table field which is ( lookup field) this field should store an integer (ID) that I lookup from a different table.
the error I have is
here is my code :
DoCmd.RunSQL ("INSERT INTO tblStocks([Stock Code], [Stock Name], [Stock Keeper1]) VALUES('" & txtCode & "','" & txtName & "'," & cmbStockKeeper1.Value & ")")
The problem simply was caused by my table design as I made the field (Stock Keeper1) indexed with no duplicate and I forgot about it, so the message was due to me trying to insert a value was already given to another record

append query failed key violation

My append query fails due to key violation but only one new records, the old records append normally just the new ones that I added fail.
DoCmd.RunSQL "INSERT INTO [Order_Item] ([Order_ID],[Item_ID],[Quantity]) Values (" & orderNumber & ", [Enter Item ID], [Enter Quantity])"
Order_ID and Item_ID are foreign keys
Access will raise an error re. key violation when you insert something into the FK via sql that isn't in the related table. You may also get a similar error for primary key violations.
Here is some code (which you'd need to adapt to your model) to check the keys exists in the related tables and that the 'mapping' does not already exist in the mapping table before you insert.
Select Case True
Case IsNull(DLookup("[ID]", "Table1", "[ID]=" & num1))
MsgBox ("ID does not exist in Table1")
Case IsNull(DLookup("[ID]", "Table2", "[ID]=" & num2))
MsgBox ("ID does not exist in Table2")
Case Not (IsNull(DLookup("[ID1]", "Map", "[ID1]=" & num1 & "And [ID2]=" & num2)))
MsgBox ("Mapping already exists")
Case Else
DoCmd.RunSQL "INSERT INTO [Map] VALUES (" & num1 & ", " & num2 & ")"
End Select
I just resolved a similar issue that was caused by a key violation issue. Two lessons that I learned might be helpful to others with similar issues:
make sure that your relationships diagram shows every table - I didn't (and the non-visible table was linked to a visible one, and that was the problem link). It's too easy to forget the links you've set up!
if you're not sure which field in the query is driving the key violation error, type a valid value into a blank field on the table - if it's the field causing the problem it'll tell you which field needs a related entry.
Of course be extra vigilant if this is a "live" system and remove any "test" data!

Append data to linked table without knowing Primary Key of main table

I have a Staff Recruitment Database. When all formalities are complete I click a button and basic data is appended to the (recruited) Staff Database .
I also have data for the shift the recruit will work: Hours, Rate of pay etc. This goes into a Linked table.
To append this data I need to know the Primary Key of the recruit. How can I append the data automatically without looking at the table where the basic data is to find the PK?
I'm using INSERT INTO. Staff Database contains the main Staff table and the linked Shifts table.
If the "main" table has an AutoNumber field as its Primary Key then immediately after performing the INSERT INTO statement you can use some code like this to retrieve the PK value you just inserted:
Dim rst AS DAO.Recordset, newPK as Long
Set rst = CurrentDb.OpenRecordset("SELECT ##IDENTITY", dbOpenSnapshot)
newPK = rst(0).Value
rst.Close
Set rst = Nothing
You can then use the newPK value as a foreign key in the related tables.
Edit re: using the new value
Based on the code sample in your comment, try this instead:
strSQL = _
"INSERT INTO tblShifts (StartDt, [To], Hours, StaffLookup) " & _
"IN ""C:\__tmp\Staff.accdb"" " & _
"SELECT qryAdd.DateStarted, qryAdd.To, qryAdd.Hours, " & newPK & " AS StaffLookup FROM qryAdd"
If [tblShifts] really is a linked table then you shouldn't need to use the IN (mydatabase) clause because a linked table will behave just like a local table in this case. Note the corrections to the syntax as well, especially the bracketing of [To] which is a reserved word in Access.
Think I have got a solution. I can retrieve the PK into the recruitment db like this:
DoCmd.RunSQL "INSERT INTO tblCBSStaffLookup ( StaffLookupCBS, NINO ) " & _
"SELECT tblStaff.ID, tblStaff.NINO " & _
"FROM tblStaff IN 'C:\Users\Peter.Home-PC\Documents\NEMS\Databases\Frontends\Staff.accdb' " & _
"WHERE (((tblStaff.NINO)=[Forms]![frmSuccess]![NINO])) "
tblCBSStaffLookup is a table I have now made in the recruitment db to collect the PK and NINO.
WHERE matches the newly arrived NINO to a form in the recruitment db which already has the NINO. I have set up constraints to make sure that NINO's are valid. I have also set up a query in the recruitment db to retrive all NINO's from the main db, so that new recruits don't get added the the main db twice.

Copy a column from one table into another table

I have tried this with ALTER TABLE to create the column followed by INSERT INTO. This kind of works, except each subsequent column starts after the previous column has ended. I guess this is how insert into works, so is there a workaround or another query I can build?
I have been trying with updates but its not working out.
For reference, these were the alter/insert queries i used.
SQL = "ALTER TABLE [results] ADD COLUMN [" & fld.Name & "_result] TEXT(25)"
db.Execute SQL
SQL = "INSERT INTO [results] ([" & fld.Name & "_result]) SELECT [Result] As
[" & fld.Name & "_result] FROM [newtable]"
db.Execute SQL
Your insert statement assumes that the results table has only one column that you need to insert data into. This is unlikely to be true, if the table already had other columns before you executed the ADD COLUMN.
You will need to keep track of the columns in the results table, and provide data (or a default value) for each column.
It is rather unusual to expand a table's structure from inside an application. What are you trying to accomplish? Are you sure you can't accomplish it better by defining fixed tables and then adding data from your application?
UPDATE
Okay, I think I understand what you're describing. On the first iteration, the ALTER TABLE creates the first column. The INSERT adds a bunch of rows that have data in this first column.
On the second interation, the ALTER TABLE creates a second column. The INSERT creates a whole bunch of new rows, but only the second column is populated. The first column is all NULL because you didn't provide values for it. And so on and so forth for the third and subsequent iterations.
If your actual intention is to duplicate the source table and its data, then you should create your results table in a single pass. You know the column structure, right? Use a CREATE TABLE statement. Then write a single INSERT statement somewhat like the following:
INSERT INTO [results]
([field1_result], [field2_result], [field3_result])
SELECT [Result] As
[field1_result, [field2_result], [field3_result]]
FROM [newtable]
Is this what you have in mind?
Before you enter into the loop create your [results] table as
SQL = "CREATE TABLE [results] SELECT [primary_key] FROM [newtable]"
db.Execute SQL
Then at every iteration of the loop execute
SQL = "ALTER TABLE [results] ADD COLUMN [" & fld.Name & "_result] TEXT(25)"
db.Execute SQL
SQL = "UPDATE [results] SET r.[" & fld.Name & "_result] = n.[Result] " &
"FROM [results] r, [newtable] n " &
"WHERE r.[primary_key] = n.[primary_key]"
db.Execute SQL
So, if you had your [newtable] at its first two iterations like
[primary_key] [Results] [primary_key] [Results]
1 A 1 D
2 B 2 E
3 C 3 F
Your [results] table (after the above two iterations) would look like
[primary_key] [fld1_result] [fld2_result]
1 A D
2 B E
3 C F

VBA EXCEL SQL CREATE TABLE syntax

Can someone please help me with the following line. I am trying to create a table that will have a column with the Id that automatically increments when a record is inserted. This is for microsoft access.
"CREATE TABLE " & tblName & " ([P_Id] integer not null AUTOINCREMENT(100, 5))"
Try the following to create an MS Access table with an auto-number field:
"CREATE TABLE [" & tblName & "] ([P_Id] integer not null IDENTITY)"
I do not know if you can specify a start-value and increment, but you can try it.