2017-04-06 205 views
0

我尝试获取具有搜索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

按照documentation for the ExecuteNonQuery() method

对于UPDATEINSERT,和DELETE语句,返回值是受该命令影响的行数。

[...]

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

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

如果我没有弄错,你必须改用​​。

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

我以前曾试过ExecuteScalar但有错误;不过,你的格式确实有效。不知道这就是人们使用Scalar方法的原因。感谢您提供的解释。 – narue1992

+0

@ narue1992:我也没有,因为我从来没有真正做过任何数据库编程:)。 - 很高兴我可以帮忙!祝你好运! –