Results 1 to 3 of 3

Thread: how the can this be incrmented and inserted to table?

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Mar 2007
    Posts
    208

    how the can this be incrmented and inserted to table?

    create table gir(idno integer unique, fname varchar(30))
    insert into gir values(1,'mam')
    then i want to enter name from an input form but the idno must enter internally by incrementing its previous values. means i have only one textbox to enter name ,but the idno should enter internally by incrementing the idno of its previous so how can i do this?
    Private Sub cmdSubmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSubmit.Click

    Dim con As SqlConnection
    Dim cmd As SqlCommand
    Dim str As String

    con = New SqlConnection("server=(local);database=master;uid=sa;pwd=test;")
    cmd = New SqlCommand(str, con)
    con.Open()


    str = "insert into gir values('" & idno& "','" & txtfname.Text & "')"
    cmd.CommandText = str
    cmd.ExecuteNonQuery()
    con.Close()
    End Sub
    how the value of idno number calculated?

  2. #2
    Smitten by reality Harsh Gupta's Avatar
    Join Date
    Feb 2005
    Posts
    2,938

    Re: how the can this be incrmented and inserted to table?

    Left it for SQL server to do it for you. In the Design mode of table, Set the Identity, Identity Seed and Identity Increment to Yes, 1 and 1 respectively, of the idno column, or whatever be the name of the column. I am assuming it to be idno.

    If you want to do it programmatically (though not recommended), get the MAX value of idno column, increment it and then pass it to your INSERT command.
    Code:
    Dim con As SqlConnection
    
    Dim str As String
    
    con = New SqlConnection("server=(local);database=master;uid=sa;pwd=test;")
    
    Dim lastIdNo as Integer
    
    str = "SELECT MAX(idno) FROM gir"
    
    Dim cmd1 as SqlCommand
    cmd1 = New SqlCommand(str, con);
    cmd1.CommandText = str
    
    con.Open()
    lastIdNo = cmd.ExecuteScalar()
    con.Close()
    
    Dim cmd As SqlCommand
    str = "insert into gir values('" & lastIdNo + 1 & "','" & txtfname.Text & "')"
    cmd = New SqlCommand(str, con)
    cmd.CommandText = str
    
    con.Open()
    cmd.ExecuteNonQuery()
    con.Close()
    End Sub
    Show Appreciation. Rate Posts.

  3. #3

    Thread Starter
    Addicted Member
    Join Date
    Mar 2007
    Posts
    208

    Re: how the can this be incrmented and inserted to table?

    Hello Harsh Gupta!
    your answer works very fine.
    thanks for your dedication!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width