存储过程的插入和更新语句有效,但是受影响的行是-1?

问题描述

我正在开发一个可以通过VB程序添加赞助者的程序。当我在sql中测试存储过程时,用于添加和更新发起人的存储过程正在运行,但是两者都引发错误,因为受影响的行返回-1。当我查看数据库时,插入/更新DID仍然有效。谁能帮我弄清楚如果插入有效,为什么受影响的行又返回-1?

这两个存储过程都返回-1。这是添加赞助者的代码

sql

GO

CREATE PROCEDURE uspAddSponsor
    @intSponsorID AS INTEGER OUTPUT,@strFirstName AS VARCHAR(50),@strLastName AS VARCHAR(50),@strStreetAddress AS VARCHAR(50),@strCity AS VARCHAR(50),@strState AS VARCHAR(50),@strZip AS VARCHAR(50),@strPhoneNumber AS VARCHAR(50),@strEmail AS VARCHAR(50)

AS 
SET NOCOUNT ON      --Report only errors
SET XACT_ABORT ON   --Terminate and rollback transaction on error

BEGIN TRANSACTION

    INSERT INTO TSponsors WITH (TABLOCKX) (strFirstName,strLastName,strStreetAddress,strCity,strState,strZip,strPhoneNumber,strEmail)
    VALUES               (@strFirstName,@strLastName,@strStreetAddress,@strCity,@strState,@strZip,@strPhoneNumber,@strEmail)

    SELECT @intSponsorID = MAX(intSponsorID) FROM TSponsors

COMMIT TRANSACTION

GO

VB代码

Private Sub AddSponsor(ByVal strFirstName As String,ByVal strLastName As String,ByVal sTraddress As String,ByVal strCity As String,ByVal strState As String,ByVal strZip As String,ByVal strPhoneNumber As String,ByVal strEmail As String)
    Dim intRowsAffected As Integer
    Dim cmdAddSponsor As New OleDb.OleDbCommand()
    Dim intPKID As Integer

    Try
        'Open DB
        If OpenDatabaseConnectionsqlServer() = False Then

            ' No,warn the user ...
            MessageBox.Show(Me,"Database connection error." & vbNewLine &
                                "The application will Now close.",Me.Text + " Error",MessageBoxButtons.OK,MessageBoxIcon.Error)

            ' and close the form/application
            Me.Close()
        End If

        'Text to call stored procedure
        cmdAddSponsor.CommandText = "EXECUTE uspAddSponsor '" & intPKID & "','" & strFirstName & "','" & strLastName & "','" & sTraddress & "','" & strCity & "','" & strState & "','" & strZip & "','" & strPhoneNumber & "','" & strEmail & "'"
        cmdAddSponsor.CommandType = CommandType.StoredProcedure

        'Call stored procedure which will insert the record
        cmdAddSponsor = New OleDb.OleDbCommand(cmdAddSponsor.CommandText,m_conAdministrator)

        'This return is the # of rows affected
        intRowsAffected = cmdAddSponsor.ExecuteNonQuery()

        'Close DB
        CloseDatabaseConnection()

        'Let user kNow what happened
        If intRowsAffected > 0 Then
            MessageBox.Show("Sponsor successfully added")
        Else
            MessageBox.Show("Sponsor not added. Error")
        End If

        Close()

    Catch ex As Exception
        MessageBox.Show(ex.Message,"Error",MessageBoxIcon.Error)
        Close()
    End Try
End Sub

有什么想法吗?

解决方法

按照Official Docs

当在连接上设置SET NOCOUNT ON时(在执行命令之前或作为命令的一部分,或作为由执行命令启动的触发器的一部分),受单个语句影响的行将停止增加受影响的行数该方法返回的结果。

我建议使用SP的返回值来指示SP是否按预期目的工作,因为您实际上并没有将受影响的行数用于其他任何事情。