Click here to Skip to main content
15,900,725 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want create table with two fields Sno(int,identity),Name(Varchar) in SQL server.
Form Looks Like

Sno -----Text box1

Name-----Text box2

SAVE Button


At first time, text box1 want to display the value 1.
Then when i save the record the data want display increment order 1,2,3......
Posted

I wouldn't advice to create an ordinal number for your records by your code. You can use for example identity[^].

However, remember that even though the number is auto incremented, you may have gaps for example if a record is deleted and so on. So this number should not used as a meaningful number, just a unique identifier. Another unique identifier mechanism is: uniqueidentifier[^]
 
Share this answer
 
Comments
Maciej Los 17-May-12 6:33am    
Good answer, +5!
Wendelius 17-May-12 7:43am    
Thanks!
Mika's answer is very good!

If you would like to get the last record from your table, there are 2 ways:
1) Using SELECT TOP(1) AND ORDER BY ... DESC
SQL
SELECT TOP(1) *
FROM YourTable
ORDER BY FieldID DESC

2) Using table Cursor[^]
SQL
DECLARE a_cursor SCROLL CURSOR FOR
DECLARE @iNum INT
SELECT [FieldID] FROM YourTable
OPEN a_cursor;
-- Fetch the last row in the cursor.
FETCH LAST FROM a_cursor
INTO @iNum;
CLOSE a_cursor;
DEALLOCATE a_cursor

SELECT @iNum
 
Share this answer
 
Comments
Wendelius 17-May-12 7:44am    
Yes, this is one possibility
Maciej Los 17-May-12 7:52am    
Thank you ;)
PunithaSabareeswari 18-May-12 1:29am    
SELECT TOP(1) *
FROM YourTable
ORDER BY FieldID DESC

ya... good idea... but at first there is no records in that table... which result i displayed
VB
    Dim da As SqlDataAdapter
         Dim i As Integer
da = New SqlDataAdapter("select id from sample order by id desc ", con)
     Dim ds As DataSet = New DataSet()
     da.Fill(ds)
     If ds.Tables(0).Rows.Count > 0 Then
         i = Convert.ToInt32(ds.Tables(0).Rows(0)(0).ToString())
         i = i + 1

         TextBox1.Text = i
     Else

         i = 1
         TextBox1.Text = i
     End If

Then

 Write simple insert quary like
insert into sample values(id,name)
 
Share this answer
 
why not try a simple solution ? Fetch the max(fieldname) from table.

something like :
SQL
Select max(Sno) from tblSomething;


Now this is the SNo of last record entered. Add one more to the value and you have next value.

P.S. - This is a bad practice doing something like this because in a scenario where "multiple users" are submitting the info, ambiguity will creep in.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900