C#存储过程或函数需要未提供的参数
本文关键字:参数 存储过程 函数 | 更新日期: 2023-09-27 18:28:31
我对C#还很陌生,我正在尝试在数据库中设置对一个需要一个参数的存储过程的调用。
我得到错误"过程或函数'SP_getName'需要参数'@username',但没有提供。"
当我为存储过程提供参数并通过SQL管理工作室运行它时,它可以正常工作。
GO
DECLARE @return_value int
EXEC @return_value = [dbo].[SP_getName]
@username = 'bob101'
SELECT 'Return Value' = @return_value
GO
然而,当我尝试调用它时,错误在于我如何传入参数,但我无法发现问题所在。
//create a sql command object to hold the results of the query
SqlCommand cmd = new SqlCommand();
//and a reader to process the results
SqlDataReader reader;
//Instantiate return string
string returnValue = null;
//execute the stored procedure to return the results
cmd.CommandText = "SP_getName";
//set up the parameters for the stored procedure
cmd.Parameters.Add("@username", SqlDbType.NVarChar).Value = "bob101";
cmd.CommandType = CommandType.Text;
cmd.Connection = this.Connection;
// then call the reader to process the results
reader = cmd.ExecuteReader();
如果能帮我发现错误,我们将不胜感激!
我也试过看这两篇帖子,但运气不好:
存储过程或函数需要未提供的参数
过程或函数需要参数,但未提供该参数
谢谢!
您已声明:
cmd.CommandType = CommandType.Text;
因此,您只是在执行:
SP_getName
它之所以有效,是因为它是批处理中的第一条语句,所以您可以在不使用EXECUTE
的情况下调用过程,但实际上并不包括参数。将其更改为
cmd.CommandType = CommandType.StoredProcedure;
或者您可以将CommandText更改为:
EXECUTE SP_getName @username;
附带说明一下,您应该避免在存储过程中使用前缀"sp_"
另一个附带说明是将using
与IDisposable对象一起使用,以确保它们被正确处理:
using (var connection = new SqlConnection("ConnectionString"))
using (var cmd = new new SqlCommand("SP_getName", connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@username", SqlDbType.NVarChar).Value = "bob101";
connection.Open();
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
// Do something
}
}
}
我遇到了这个问题,但这与命令类型的参数名称无关。我的问题是,当C#调用SP时,对于每个没有值的参数,都会传递"default"关键字(我在SQL Profiler中找到它):
... @IsStop=0,@StopEndDate=default,@Satellite=0, ...
在我的情况下,我的参数类型是DateTime:
@StopEndDate datetime
我通过在存储过程中设置此参数的默认值解决了我的问题:
@StopEndDate datetime=null
尝试删除@
:
cmd.Parameters.Add("username", SqlDbType.NVarChar).Value = "bob101";