It sounds like you either have an existing employee with an existing employee ID, or you are creating a new employee and need the stored procedure to return a newly created employee ID. Is this correct?
If so, then you might try something like this:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim sqlConn As New SqlClient.SqlConnection
Dim intEmployeeID As Integer
Dim perEmployee_ID As New SqlParameter("@employee_id", SqlDbType.Int)
Dim sqlCmd As New SqlCommand
Dim _blnUpdated As Boolean = True
If _blnUpdated Then
sqlCmd.CommandText = "sp_ManageEmployee"
perEmployee_ID.Value = intEmployeeID
perEmployee_ID.Direction = ParameterDirection.Input
Else
sqlCmd.CommandText = "sp_ManageEmployee"
perEmployee_ID.Value = -1
perEmployee_ID.Direction = ParameterDirection.InputOutput
End If
sqlCmd.Parameters.Add(perEmployee_ID)
sqlCmd.ExecuteNonQuery()
If _blnUpdated Then
intEmployeeID = Convert.ToInt32(sqlCmd.Parameters("@employee_id").Value)
End If
End Sub
You can direct both conditions to the same stored procedure: if the employee id parameter is -1 then do the "add new" block; otherwise do the other block. This will help you keep related code in the same stored procedure, which will make maintenance a bit easier. Make sure that the @employee_id parameter in your stored procedure is flagged for output:
CREATE PROCEDURE sp_ManageEmployee
@employee_id INT OUTPUT
...
If you are adding a new employee, set the parameter direction in your code to be input/output. Assuming that the
EmployeeId
field is flagged as
Identity
, you can use
SELECT @employee_id = SCOPE_IDENTITY()
after your insert to get the newly created id number. Because the parameter is flagged for output, it will be passed back up to your calling code.