Question

Dim con As New SqlConnection
    Dim cmd As New SqlCommand
    Dim cmd1 As New SqlCommand
    Dim cmd2 As New SqlCommand
    Dim cmd3 As New SqlCommand
    Dim rd, rd1, rd2 As SqlDataReader
    Dim lastid As String

    con.ConnectionString = "Data Source=ELMAR-PC\ELMAR;Initial Catalog=users;Integrated Security=True;"
    cmd.Connection = con
    cmd1.Connection = con
    cmd2.Connection = con
    cmd3.Connection = con
    con.Open()

    If TextBox1.Text = "" Or RadioButton3.Checked = False And RadioButton4.Checked = False Then
        MsgBox("Please fill all the required fields", vbCritical)
    End If


    cmd.CommandText = "insert into tblquestion (question,type)values ('" + TextBox1.Text + "','" + TextBox10.Text + "') "
    cmd1.CommandText = "SELECT @@IDENTITY "
    ' TextBox11.Text = Val(cmd1.CommandText)
    lastid = cmd1.CommandText
    cmd2.CommandText = "update tblquestion set question_id ='" + lastid + "' where ID='" + lastid + "'limit 1"
    rd = cmd.ExecuteReader
    con.Close()
Was it helpful?

Solution

Try this:

' Validation
If TextBox1.Text = "" Or RadioButton3.Checked = False And RadioButton4.Checked = False Then
    MsgBox("Please fill all the required fields", vbCritical)
    Exit Sub
End If

' Open connection
Dim con As New SqlConnection
con.ConnectionString = "Data Source=ELMAR-PC\ELMAR;Initial Catalog=users;Integrated Security=True;"
con.Open()

Dim lastid As Int32

'Execute first insert
Dim cmd As New SqlCommand
cmd.Connection = con
cmd.CommandText = "insert into tblquestion (question,type)values ('" + TextBox1.Text + "','" + TextBox10.Text + "'); SELECT SCOPE_IDENTITY()"

lastid = Convert.ToInt32(cmd.ExecuteScalar()) 'this will give you the identity
cmd.Dispose()

'Execute second insert with lastid
Dim cmd1 As New SqlCommand
cmd1.Connection = con
cmd1.CommandText = "update tblquestion set question_id ='" + lastid + "' where ID='" + lastid + "'limit 1"
rd = cmd1.ExecuteNonQuery()
cmd1.Dispose()

'Close connection
con.Close()

OTHER TIPS

You can combine both INSERT and SELECT @@IDENTITY into a single command text. And then use executeScalar to retrieve the value.

cmd.CommandText = "insert into tblquestion (question,type) values ('" + TextBox1.Text + "','" + TextBox10.Text + "'); "
cmd.CommandText &= "SELECT @@IDENTITY "
lastid = cmd.ExecuteScalar() 'this will give you the identity

Side note: Instead of using string concatenation above to construct your query, use parametrized queries - it will save you a lot of pain, including SQL Injection.

EDIT: I still recommend getting the identity at the time of insertion. But if you need to retrieve it elsewhere in code at another time, you can use

cmd1.CommandText = "SELECT MAX(ID) FROM tblquestion"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top