返回存储过程值

时间:2017-04-06 21:53:06

标签: vb.net stored-procedures count

我尝试获取具有搜索到的ID的行数。 我用它来检查重复项。

我不确定如何将计数作为变量返回,以便我可以比较它。 我有支票If cmd.ExecuteNonQuery() = 0 Then,但它总是-1。 我尝试过制作Int row as Integer = cmd.ExecuteNonQuery()并始终为-1。

所以我的问题是......在我执行cmd.ExecuteNonQuery()之后如何获取计数金额的数据集值并将其分配给Dim count as Integer = ....

之类的值

存储过程:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE UserCheck
-- Add the parameters for the stored procedure here
@ID bigint
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

   SELECT COUNT(*) FROM tbl WHERE ID= @ID;
END
GO

Vb.net

   Dim CS1 As String = ModuleGlobals.connectionString

    Using con As New SqlConnection(CS1)

        Dim cmd As New SqlCommand("dbo.UserCheck", con)
        con.Open()
        'specify that it is a stored procedure and not a normal proc
        cmd.CommandType = System.Data.CommandType.StoredProcedure

        cmd.Parameters.AddWithValue("@ID", TextBox3.Text)
        'Dim count As Integer = cmd.ExecuteNonQuery()

        If cmd.ExecuteNonQuery() = 0 Then

            Dim CS As String = ModuleGlobals.connectionString
            Using con2 As New SqlConnection(CS)

                Dim cmd2 As New SqlCommand("dbo.Create", con2)
                con2.Open()

                ...add parameters here

                cmd2.ExecuteNonQuery()
                con2.Close()
            End Using
        Else
            MsgBox("No user was created")
        End If
        con.Close()
    End Using

1 个答案:

答案 0 :(得分:1)

根据documentation for the ExecuteNonQuery() method

  

对于更新 INSERT DELETE 语句,返回值是受命令影响的行数。

     

[...]

     

对于所有其他类型的语句,返回值为-1 。如果发生回滚,则返回值也为-1。

由于您的存储过程只调用SELECT,因此它将始终返回-1。

如果我没弄错,你必须使用ExecuteScalar() method

Dim count As Integer = CType(cmd.ExecuteScalar(), Integer)