存储过程返回varchar

时间:2010-07-01 13:41:11

标签: c# .net sql sql-server vb.net

我正在尝试创建返回varchar值的存储过程,以及我需要在文本框中显示的值。

这是存储过程的代码:

Create PROCEDURE Status @id_doc int, @Name varchar(50) OUTPUT
AS
select  @Name =items.name    
from Doc,Items where @id_doc=IDN and doc.IDN=Items.ID 
return @Name 

这是vb.net中的代码,我需要在textbox中显示返回值:

Public Sub Current()
        Dim dtc As New Data.DataTable
        Dim dr As SqlClient.SqlDataReader
        Dim da As New SqlClient.SqlDataAdapter
        Dim cmd As New SqlClient.SqlCommand
        Dim id_doc As Integer
        Dim dset As New DataSet
        Dim recordset As DataRow
        Dim Name As String

        Try
            id_doc = idDocExplorer
            cmd.Connection = pubCon
            cmd.CommandType = CommandType.StoredProcedure
            cmd.CommandText = "Status"
            cmd.Parameters.Add("@id_doc", id_doc)
            cmd.Parameters.Add("@Name ", SqlDbType.VarChar)
            cmd.Parameters("@Name ").Direction = ParameterDirection.Output
            cmd.ExecuteScalar()

            Name = cmd.Parameters("@Name ").Value
           TextBox1.text=Name
        Catch ex As Exception
            MsgBox(ex.Message)
        Finally
            dtc = Nothing
            dr = Nothing
            da = Nothing
        End Try
    End Sub

当我尝试执行此代码时,我收到此消息的异常:

“String [1]:Size属性的大小无效。”

我做错了什么?谢谢!

3 个答案:

答案 0 :(得分:3)

创建时,您需要指定@Name参数的size

"@Name "字符串中还有一个额外的空格 - 它应该是"@Name"

cmd.Parameters.Add("@Name", SqlDbType.VarChar, 50)

答案 1 :(得分:2)

尝试更改:

cmd.Parameters.Add("@Name", SqlDbType.VarChar)

为:

cmd.Parameters.Add("@Name", SqlDbType.VarChar, 50)

定义输出参数的大小

答案 2 :(得分:0)

你应该尝试调用ExecuteNonQuery而不是ExecuteScalar