从存储过程获取响应

时间:2012-01-06 04:41:29

标签: sql vb.net stored-procedures parameters sql-server-2008-r2

嘿所有我想收到SP回复的回复,我用VB.net打电话。这是我的代码:

  connection.Open()
  command.CommandType = CommandType.StoredProcedure
  command.CommandText = "RPT_C_S_H"          
  command.Parameters("@theOutput").Direction = ParameterDirection.Output  'returns 0 if bad, 1 if good
  Dim dataReader As SqlDataReader = command.ExecuteReader()

所以现在我只做一个

dim returnedValue as integer = 0

Do While dataReader.Read()
     returnedValue = dataReader(0)
Loop

以获取返回值?

任何帮助都会很棒!谢谢!

大卫

更新

connection.Open()
command.CommandType = CommandType.StoredProcedure
command.CommandText = "RPT_C_S_H"
Dim sqlParReturn As System.Data.SqlClient.SqlParameter = command.Parameters.Add("@theOutput", SqlDbType.SmallInt)
sqlParReturn.Direction = ParameterDirection.ReturnValue
command.ExecuteNonQuery()
Dim returnedValue As Integer = CInt(sqlParReturn.Value)

更新#2

  Dim sqlParReturn1 As System.Data.SqlClient.SqlParameter = command.Parameters.Add("@Error_Code", SqlDbType.Int)
  Dim sqlParReturn2 As System.Data.SqlClient.SqlParameter = command.Parameters.Add("@Err_Msg", SqlDbType.VarChar)
  Dim sqlParReturn3 As System.Data.SqlClient.SqlParameter = command.Parameters.Add("@result", SqlDbType.Bit)

  sqlParReturn1.Direction = ParameterDirection.Output
  sqlParReturn2.Direction = ParameterDirection.Output
  sqlParReturn3.Direction = ParameterDirection.Output

  command.ExecuteNonQuery()
  Dim returnedValue1 As String = sqlParReturn1.Value
  Dim returnedValue2 As String = sqlParReturn2.Value
  Dim returnedValue3 As String = sqlParReturn3.Value

SP看起来像这样:

  ALTER PROCEDURE [dbo].[CSS_SP_Job_Return] (
    @job INT,
    @UserID VARCHAR(50),
    @Printer_Name VARCHAR(30),
    @Error_Code int OUTPUT,
    @Err_Msg  varchar (1000) OUTPUT,
    @result BIT OUTPUT
  )

我一直收到错误:字符串[4] size属性的大小无效

这是什么意思?

2 个答案:

答案 0 :(得分:1)

我更倾向于让你的程序返回一个INT并执行一个ExecuteScalar来获得结果。

答案 1 :(得分:1)

你会做这样的事情来从SQL参数中读出值:

Do While dataReader.Read()
     '' do something with your data here!
Loop

Dim value = command.Parameters("@theOutput").Value

但这只会在 之后才能完成读取数据读取器中的所有行(假设您的存储过程确实确实使用{{1}返回了一些数据}}语句 - 否则使用SELECT代替数据读取器)