我正在尝试使用以下代码从存储过程返回varchar:
Dim uname As SqlCommand = New SqlCommand("userName", uconnect)
uname.CommandType = CommandType.StoredProcedure
Dim outVal As SqlParameter = uname.Parameters.Add("userName", SqlDbType.VarChar)
uname.Parameters.AddWithValue("userID", userLog)
uname.Parameters.AddWithValue("@userName", " ")
outVal.Direction = ParameterDirection.Output
uname.ExecuteReader() 'This line trows exception saying:
' "String[1]: the Size property has an invalid size of 0."
uconnect.Close()
Dim name As String = outVal.Value
这是SP代码:
ALTER PROCEDURE [dbo].[userName]
-- Add the parameters for the stored procedure here
@userID int,
@userName varchar(30) OUTPUT
AS
SELECT @userName = owner FROM users WHERE user_id = @userID
我也尝试设置返回的varchar参数的大小,如下所示:
uname.Parameters.Add(“userName”,SqlDbType.VarChar, 30 )
但如果我在上面的行中添加size参数,当我运行一个程序时,它会抛出一个新的异常,说:“存储过程UserName指定的参数太多了。”
答案 0 :(得分:1)
SqlParameter.Add有许多重载,但在这种情况下需要使用的是您尝试使用列大小的表单:
uname.Parameters.Add("userName", SqlDbType.VarChar, 30)
您获得的错误是因为您已经将userName参数声明了两次 - 一次是userName,再次声明为@userName - 这会导致三个参数被发送到Sql Server,当您的存储过程只接受两个时。删除这一行,一切都会好的:
' Remove this line
uname.Parameters.AddWithValue("@userName", " ")
答案 1 :(得分:0)
如果您的代码非常简单,那么只选择结果并执行标量可能更容易。
Dim uname As SqlCommand = New SqlCommand("userName", uconnect)
uname.CommandType = CommandType.StoredProcedure
uname.Parameters.AddWithValue("userID", userLog)
Dim name As String
name = uname.ExecuteScalar()
uconnect.Close()
像这样的sproc:
ALTER PROCEDURE [dbo].[userName]
-- Add the parameters for the stored procedure here
@userID int,
AS
SELECT owner FROM users WHERE user_id = @userID
注意:我是一名c#程序员,如果这不完美,那就很抱歉。