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.
Related
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.
I have a user form that inserts data into "user" table and "organizer" table when I click a button, user data gets inserted with no problem, but it prompts me to enter the value (organization_name) again in a small dialogue box -which supposed to take from the text field and insert into organizer table- ,
then gives me an error saying "ms access set one row null due to validation rule violation"
NOTE: I didn't put any validation rule for the "organization_name" anywhere
Private Sub InsertSqlIntoOrgTable()
Dim orgName As String, SqlOrgNameInsert As String
orgName = txtOrgName.Value 'takes the value from text field
SqlOrgNameInsert = "INSERT INTO ORGANIZER (ORG_NAME) VALUES (" & orgName & ") "
DoCmd.RunSQL SqlOrgNameInsert
End Sub
SqlOrgNameInsert = "INSERT INTO ORGANIZER (ORG_NAME) VALUES ('" & orgName & "') "
if the field name in table ORGANIZER is really ORG_NAME. Show us your complete table definition in case that this doesn't solve your problem. Because in your last question you posted:
sqlOrgInsertUsrId = "INSERT INTO ORGANIZER (USER_ID) VALUES (" & orgUserId & ")"
Both inserts run into the same table but try to create new independent rows. If USER_ID is primary key then your insert into ORG_NAME can't work that way.
You should learn more about SQL.
I am using the following code to insert data in an access table from SQL using a recordset. This table is further used for other operations. While this is inserting the data into the table perfectly, the time taken by this huge. Should I use any other method to insert data into the table to reduce the time taken?
Do Until rs.EOF
DoCmd.RunSQL "INSERT INTO Table (Alpha,Beta,Gamma) VALUES(" & _
rs.Fields(0).Value & ",'" & rs.Fields(1).Value & "'," & rs.Fields(2).Value _
& " );"
rs.MoveNext
Loop
Create a linked table to the SQL table, say it's called MyLinkedTable
Create an Append query to append to your local Access table from your linked table. It will look something like this: INSERT INTO MyAccessTable (Field1,Field2...) SELECT Field1,Field2... FROM MyLinkedTable;
If you could select the data in the SQL UPDATE statement instead looping in VBA it would take a fraction of the time as all the work would be done by the server side.
You just need to do an INSERT INTO SELECT. We need more information on your RecordSet but you probably do not need it.
'Here we go, with just one line!
DoCmd.RunSQL "INSERT INTO Table (Alpha,Beta,Gamma) SELECT column1, column2, column2 FROM YourTable"
The SELECT statement is probably the same as the one you used for opening your Recordset.
Good luck!
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.
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