473,385 Members | 1,337 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,385 software developers and data experts.

Incrementing a field

How can I increment a field without using Autonumber,
like reading from its last value and then increment it?
I'm new to vb.NET and really need a detailed explanation.
Nov 18 '11 #1
10 7016
I believe you are talking about autonumbers for fields in a database, right? In vb.net simply use a command (and a dataReader if you need more stuff) on a query like

INSERT INTO yourTable SELECT ((select count(*) from yourTable) + 1), ...

But be careful, when you delete a row from that table, the COUNT(*) might return an already existing index and cause an error.

EDIT: you can also do (if this is what you wanted)

INSERT INTO yourtable SELECT ((select MAX(yourTable_index) from yourTable)+1),...
Nov 18 '11 #2
Hi, thank you for your kind help.
I have tried the code you gave me but it doesn't seem to work.
Ican't store the ID nor increment the Code.
Here are my codes below,


Column "Code" is the one that suppose to increment as I store new "ID".



Expand|Select|Wrap|Line Numbers
  1.          Private Sub addbtn3_Click(ByVal sender As System.Object, ByVal e As      System.EventArgs) Handles addbtn3.Click
  2.  
  3.  Dim intaffected As Integer
  4.         Dim intaffected2 As Integer
  5.         Dim dsClassification As New DataSet
  6.         dsClassification = New DataSet
  7.         Dim strID As String
  8.         Dim Code As Integer
  9.  
  10.         'Prompt the user to enter a ID
  11.         If txtID.Text = "" Then
  12.  
  13.             MessageBox.Show("Please Enter ID!")
  14.  
  15.         End If
  16.  
  17.         If txtID.Text <> "" Then
  18.             'Retrieve Column from database to check if there is any duplicate
  19.             'Check duplicate2 is in the Service Object and whatever is entered in the text box
  20.             'will be compared to the ID Column'
  21.             dsClassification = CheckDuplicate2(txtID.Text)
  22.             strID= txtID.Text
  23.             'If its true/if a duplicate ID is found,
  24.             If dsClassification.Tables(0).Rows.Count = 1 Then
  25.                 'Show Duplicate is found and ask the user to enter new ID
  26.                 MessageBox.Show("Duplicate Found. Please Enter New ID")
  27.                 txtID.Text = ""
  28.  
  29.  
  30.             Else
  31.  
  32.  
  33.                 'new record
  34.                 intaffected = AddID(txtID.Text)
  35.  
  36.  
  37.                 MessageBox.Show("No Duplicate Found! Adding Successful! ")
  38.  
  39.                 txtID.Text = ""
  40.             End If
  41.  
  42.  
  43.             If intaffected = 0 Then
  44.  
  45.  
  46.  
  47.             End If
  48.         End If
  49.  
  50.  
  51.     End Sub
  52.  
Expand|Select|Wrap|Line Numbers
  1. Public Function AddID(ByVal ID As String)
  2.         Dim strSql As String
  3.         Dim dstemp As New DataSet
  4.         Dim intaffected As Integer
  5.  
  6.         Try
  7.             build()
  8.             'Using a SQL statement INSERT INTO to include data to access table
  9.             strSql = "INSERT INTO tblClassification SELECT ((select MAX(Code)from tblClassification)+1 ,[ID]) VALUES ('" & ID & "')"
  10.  
  11.  
  12.  
  13.             myCommand = New OdbcCommand(strSql, myConn)
  14.             myCommand.CommandTimeout = 50
  15.  
  16.             connect()
  17.  
  18.             intaffected = myCommand.ExecuteNonQuery()
  19.  
  20.             Return intaffected
  21.  
  22.         Catch ex As Exception
  23.             Try
  24.  
  25.             Catch odbcEx As OdbcException
  26.                 MessageBox.Show(odbcEx.Message & odbcEx.StackTrace)
  27.             End Try
  28.  
  29.             Return intaffected
  30.         Finally
  31.             disconnect()
  32.         End Try
  33.  
  34.     End Function
  35.  
  36.  
Nov 19 '11 #3
Expand|Select|Wrap|Line Numbers
  1. strSql = "INSERT INTO tblClassification SELECT ((select 
  2. MAX(Code)from tblClassification)+1 ,[ID]) VALUES ('" & ID & "')"
  3.  
The problem is here, in your AddID function. One tip i can give you is to research the INSERT INTO SELECT combination on google to get a better understanding, and the INSERT INTO VALUES also. What i mean is this(just an example):

Expand|Select|Wrap|Line Numbers
  1. INSERT INTO table(ID,table_string,table_number) VALUES (1,'abc',3)
  2. (or something similar)
is equivalent to:

Expand|Select|Wrap|Line Numbers
  1. INSERT INTO table(ID,table_string,table_number) SELECT 1,'abc',3
Now if instead of the ID you want to put something that increments itself (basically something that you don't need to or cannot know the value of), you put it like:

Expand|Select|Wrap|Line Numbers
  1. INSERT INTO table(ID,table_string,table_number) SELECT ((SELECT MAX(ID) FROM TABLE)+1) , 'abc' , 3
Make sure your ID field in the database is of type INT or Number or something similar, and not varchar or other types of strings.

Adjust this query to what your table has and, in order to make it easier to test everything, try running it directly on your database (not from code) and see what happens and if it works.

I don't know what kind of database you have and there could be some syntax differences (i'm working with transact-sql, but i believe it should also work on what you have).

Also, it's not very clear from your code, but are you trying to insert ONLY an ID into your table and still asking the user for its value? IDs (unique indexes) shouldn't be input from the keyboard usually. They are meant to keep track of the rows in the table, and this table should usually contain other data (i.e. more columns). Try reading about designing database tables to get a better understanding of these.

Now some other small issues:

Expand|Select|Wrap|Line Numbers
  1. Dim dsClassification As New DataSet
  2. dsClassification = New DataSet
I believe you can leave the first line only, or Dim dsClassification As DataSet = New DataSet

Secondly, research the InputBox function for asking the user to input a value and returning it, i believe it will ease up your work (http://msdn.microsoft.com/en-us/libr...=VS.90%29.aspx).

Hope this helped. Good luck
Nov 19 '11 #4
I've changed the ID to description because since you've said its
unique indexes.. so here what I actually suppose to do,


Access data:

Column 1: CODE (primary key)
Column 2: DESCRIPTION


CODE DESCRIPTION

1 MAMMAL
2 REPTILE
3 AMPHIBIAN

Its like this, as I enter a new DESCRIPTION,
and when I click the add button, it suppose to be stored into the data table.
And the first column (CODE) should increment, so when I entered a new data,BIRDS, table should be like:

CODE DESCRIPTION

1 MAMMALS
2 REPTILES
3 AMPHIBIANS
4 BIRDS



ps. sorry for confusing you, I'm confused myself..
Nov 20 '11 #5
Don't worry about it. So you should have something like this(in vb.net):

Expand|Select|Wrap|Line Numbers
  1.  
  2. Dim description As String
  3. ' ...
  4. ' Here you determine the value of description
  5. ' by asking the user for it or something (see Inputbox function).
  6. ' So you should end up having description = "Mammals" and so on.
  7. ' ...
  8. strSql = "INSERT INTO yourTable(Code,Description) SELECT (SELECT isnull(MAX(Code),0) FROM yourTable)+1, '" + description + "'"
  9.  
  10. ' now you run your sqlCommand for every value of description in order to insert it in the table.
  11.  
NOTE: isnull(MAX(Code),0) returns MAX(Code) if Code is not null (i.e. if the table entry is empty), and 0 otherwise. This helps you insert the first value in the table, since MAX(Code) with Code being NULL gives an error, so you need this test before. Also the syntax of isnull might vary according to your database, so search for a function that does exactly the same

isnull(x, value) => returns value if x=null.
Nov 20 '11 #6
It didn't increment my Code column nor store the new description
:(
How so?


Expand|Select|Wrap|Line Numbers
  1. Public Function AddClassification(ByVal Description As String)
  2.         Dim strSql As String
  3.         Dim dstemp As New DataSet
  4.         Dim intaffected As Integer
  5.  
  6.         Try
  7.             build()
  8.             'Using a SQL statement INSERT INTO to include data to access table
  9.             strSql = "INSERT INTO tblClassification(Code, Description) SELECT (SELECT isnull(MAX(Code),0) FROM tblClassification)+1, '" & Description & "'"
  10.  
  11.  
  12.  
  13.             myCommand = New OdbcCommand(strSql, myConn)
  14.             myCommand.CommandTimeout = 50
  15.  
  16.             connect()
  17.  
  18.             intaffected = myCommand.ExecuteNonQuery()
  19.  
  20.             Return intaffected
  21.  
  22.         Catch ex As Exception
  23.             Try
  24.  
  25.             Catch odbcEx As OdbcException
  26.                 MessageBox.Show(odbcEx.Message & odbcEx.StackTrace)
  27.             End Try
  28.  
  29.             Return intaffected
  30.         Finally
  31.             disconnect()
  32.         End Try
  33.  
  34.     End Function
  35.  
  36.  


Does it have to do with my click button?


Expand|Select|Wrap|Line Numbers
  1. Private Sub addbtn3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles addbtn3.Click
  2.         Dim intaffected As Integer
  3.  
  4.         Dim dsClassification As DataSet = New DataSet
  5.  
  6.         Dim strdescription As String
  7.  
  8.  
  9.         'Prompt the user to enter a Classification Description
  10.         If txtDescription.Text = "" Then
  11.  
  12.             MessageBox.Show("Please Enter Description!")
  13.  
  14.         End If
  15.  
  16.         If txtDescription.Text <> "" Then
  17.             'Retrieve Column from database to check if there is any duplicate
  18.             'Check duplicate2 is in the Service Object and whatever is entered in the text box
  19.             'will be compared to the 'Classification Description Column'
  20.             dsClassification = CheckDuplicate2(txtDescription.Text)
  21.             strdescription = txtDescription.Text
  22.             'If its true/if a duplicate Description is found,
  23.             If dsClassification.Tables(0).Rows.Count = 1 Then
  24.                 'Show Duplicate is found and ask the user to enter new description
  25.                 MessageBox.Show("Duplicate Found. Please Enter New Description")
  26.                 txtDescription.Text = ""
  27.  
  28.  
  29.             Else
  30.  
  31.  
  32.                 'new record
  33.                 intaffected = AddClassification(Description.Text)
  34.  
  35.  
  36.                 MessageBox.Show("No Duplicate Found! Adding Successful! ")
  37.  
  38.                 txtDescription.Text = ""
  39.             End If
  40.  
  41.  
  42.             If intaffected = 0 Then
  43.  
  44.  
  45.  
  46.             End If
  47.         End If
  48.  
  49.  
  50.     End Sub
  51.  
Nov 20 '11 #7
Did it give you any error? Try running that insert query directly on the database (NOT from code). Something like:

INSERT INTO tblClassification(Code, Description) SELECT (SELECT isnull(MAX(Code),0) FROM tblClassification)+1, 'Mammals'

and see what happens. It might be a syntax problem like i said before. It depends on what kind of database you are using and if it connects to it properly, and if you have enough rights to insert data into it.

I've already tested it in sql server 2008 on an empty table with 2 fields(an int and a varchar) and it works just fine. If the query inserts the data properly in your table too then it's something wrong in the code. Please try this and let me know what happens, as well as what database you have (i mean with what did you create it, MS Access, MS Sql server 2008 etc).

PS: also in your AddClassification function, put the disconnect() BEFORE each Return statement. I believe it might not close the connection thus making it unable to see any modification on your database.
Nov 20 '11 #8
I'm using MsAccess 2007 for the database..
And I've tried the above and still it doesn't store.
As in it has no error or syntax, it just can't store :(

Is there any other way like using loops?
Nov 20 '11 #9
Not the loops are the problem. It's strange there is no error. Did you do the following? (i've made the text bold and inclined)

Expand|Select|Wrap|Line Numbers
  1. Try
  2.             build()
  3.             'Using a SQL statement INSERT INTO to include data to access table
  4.             strSql = "INSERT INTO tblClassification(Code, Description) SELECT (SELECT isnull(MAX(Code),0) FROM tblClassification)+1, '" & Description & "'"
  5.  
  6.  
  7.             connect()
  8.             myCommand = New OdbcCommand(strSql, myConn)
  9.             myCommand.CommandTimeout = 50
  10.  
  11.             intaffected = myCommand.ExecuteNonQuery()
  12.  
  13.             disconnect() 
  14.             Return intaffected
  15.  
  16.         Catch ex As Exception
  17.             'Try
  18.  
  19.             'Catch odbcEx As OdbcException
  20.             MessageBox.Show(Ex.Message & Ex.StackTrace)
  21.             'End Try
  22.  
  23.             disconnect()
  24.             Return intaffected
  25.         
  26.  
  27.         End Try
  28.  
  29.  
You dont need the Finally statement in this case anymore. Also i don't know what connect() and disconnect() are actually doing. Do you have a global variable called myConn ? Are your ODBC data sources set properly in Windows?

If all of this doesn't do the trick, try replacing

(SELECT isnull(MAX(Code),0) FROM tblClassification)+1

with

(SELECT NZ(MAX(Code),0) FROM tblClassification)+1

in the query. Please try all of these things and tell me the results. It should work or at least give an error or something.

Did you run the query directly from MS Access, as i wrote in my previous post's example? (replace isnull with NZ if it gives an error). Please do this and say what happens.
Nov 20 '11 #10
what is ( CheckDuplicate2 ) is it function or inbuilt etc!!!!
Feb 24 '16 #11

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

Similar topics

3
by: Poul Møller Hansen | last post by:
Hi, I need an auto incrementing field that will contain values like N000001, N000002, N000003 etc. I think the way is to use the value from an identity field in a stored procedure that is...
1
by: Dave Stone | last post by:
I find with a table in datasheet view, if a Number field is blank, and I fill it in for a series of rows (more than 2) with values incrementing by 1 or 2 (only), then Access 'helpfully' fills in...
1
by: K. Davis | last post by:
I need to increment the maximum value of a field of a table by 1 when a form opens a blank record. (e.g. =max(!![trip_number}) so the logic and references are working at the form level. I've...
2
by: Tim Vadnais | last post by:
Hi, My boss wants to add some logging functionality to some of our tables on update/delete/insert. I need to log who, when, table_name, field name, original value and new value for each record,...
2
by: acortez | last post by:
How can I possibly get the value from a newly inserted record in access db where the datafield type is autoincrement? I don't think querying for the newly inserted data is the best solution. or is...
3
by: Adam Sandler | last post by:
Hello, I'm able to reproduce my problem but I haven't been able to figure out why it is happening. MS does have an article about such behavior in...
4
by: flumonion | last post by:
Hi, Does anyone know how i could add a incrementing field to a select statement. at the moment i have the following: SELECT X,Y, (SELECT COUNT(*) FROM dbo.tbldo e2 WHERE e2.doid <=...
1
by: asandiego | last post by:
Hey guys, this is my first post here but have been checking this site a lot for anything I need. I hope someone can lead me to what I should do or just an idea to what can be done. What I'm...
3
by: bkberg05 | last post by:
Hi - I have a field called Sequence on a continuous subform. The Sequence field belongs to a table called Project_Draw. This table has many 'Draw' records for each 'Project' record. So then the...
2
by: JonHuff | last post by:
looking for MS Access VBA code to do the following: I am trying to assign incrementing numbers ( ie - 1-10) to records in an existing table by date and pull a 10% random sample from that table based...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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...

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.