且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

VB.Net-请求ID,在保存时显示自动ID

更新时间:2023-02-16 12:34:20

听起来您是现有员工,还是现有员工ID,或者您正在创建新员工员工,并且需要存储过程来返回新创建的员工ID.这是正确的吗?

如果是这样,那么您可以尝试执行以下操作:
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


您可以将两个条件都定向到相同的存储过程:如果employee id参数为-1,则执行添加新"块;否则,请执行其他步骤.这将帮助您将相关代码保留在相同的存储过程中,这将使维护变得更加容易.确保将存储过程中的@employee_id参数标记为输出:


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
    ...



如果要添加新员工,请在代码中将参数方向设置为输入/输出.假定EmployeeId字段标记为Identity,则在插入后可以使用SELECT @employee_id = SCOPE_IDENTITY()来获取新创建的ID号.由于该参数已标记为要输出,因此它将被传递回您的调用代码.



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.