/* -- The following snippet writes the value of the latest INSERT statement's identity field to the browser -- */

int nInsertId;
String sSql = "INSERT INTO my_table (my_field) VALUES (@Value); SELECT SCOPE_IDENTITY();";
SqlConnection oConn = new SqlConnection(sConnString);
SqlCommand oCommand = new SqlCommand(sSql, oConn);

oCommand.Parameters.Add("@Value", SqlDbType.VarChar, 255).Value = sMyValue;

try {
  oConn.Open();
  nInsertId = Convert.ToInt32(oCommand.ExecuteScalar());
} catch (Exception exc) {
  // Handle error
} finally {
  if (oConn.State == ConnectionState.Open) {
    oConn.Close();
  }
}

Response.Write(nInsertId.ToString());
' The following snippet writes the value of the latest INSERT statement's identity field to the browser

Dim nInsertId As Integer
Dim sSql As String = "INSERT INTO my_table (my_field) VALUES (@Value); SELECT SCOPE_IDENTITY();"
Dim oConn As New SqlConnection(sConnString)
Dim oCommand As New SqlCommand(sSql, oConn)

oCommand.Parameters.Add("@Value", SqlDbType.VarChar, 255).Value = sMyValue

Try
  oConn.Open()
  nInsertId = Convert.ToInt32(oCommand.ExecuteScalar())
Catch Exception exc
  ' Handle error
Finally
  If oConn.State = ConnectionState.Open Then
    oConn.Close()
  End If
End Try

Response.Write(nInsertId.ToString())