C# 存储过程期望通过其提供的
我陷入了困境。我在c#应用程序中收到错误“过程或函数'SP_RPT_User'需要参数'@deptName',但未提供参数。”。甚至我也复制并替换了这个名字。仍然没有成功C# 存储过程期望通过其提供的,c#,sql-server,stored-procedures,C#,Sql Server,Stored Procedures,我陷入了困境。我在c#应用程序中收到错误“过程或函数'SP_RPT_User'需要参数'@deptName',但未提供参数。”。甚至我也复制并替换了这个名字。仍然没有成功 public DataTable SP_RPT_User(int loggedid, String deptName, String OfficeName, String empType) { int updatedrows = 0; DataTable table = new Da
public DataTable SP_RPT_User(int loggedid, String deptName, String OfficeName, String empType)
{
int updatedrows = 0;
DataTable table = new DataTable();
try
{
cCommand = new System.Data.SqlClient.SqlCommand("SP_RPT_User", connection);
cCommand.CommandType = CommandType.StoredProcedure;
cCommand.Parameters.Add("@loggedId", SqlDbType.Int).Value = loggedid;
cCommand.Parameters.Add("@deptName", SqlDbType.NVarChar, 200).Value = deptName;
cCommand.Parameters.Add("@OfficeName", SqlDbType.VarChar, 150).Value = OfficeName;
cCommand.Parameters.Add("@empType", SqlDbType.VarChar, 150).Value = empType;
cCommand.CommandTimeout = 90000;
connection.Open();
updatedrows = cCommand.ExecuteNonQuery();
using (var da = new SqlDataAdapter(cCommand))
{
cCommand.CommandType = CommandType.StoredProcedure;
da.Fill(table);
}
}
catch (Exception Ex)
{
connection.Close();
// return -100;
}
finally
{
connection.Close();
}
return table;
}
存储过程
ALTER PROCEDURE [dbo].[SP_RPT_User]
-- Add the parameters for the stored procedure here
@loggedId int,
@deptName NVarChar(200),
@OfficeName varchar(150),
@empType varchar(150)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
declare @sql nvarchar(max);
set @sql ='SELECT ...'; // here is one query
if(@deptName != '')
set @sql = @sql + ' and dbo.TB_Department.name like ''%'+@deptName+'%''';
Declare @params nvarchar(500)
SELECT @params ='@loggedId int,'+
'@deptName NVarChar(200),'+
'@OfficeName varchar(150),'+
'@empType varchar(150)'
exec sp_executesql @sql, @params,@loggedId,@deptName,@OfficeName,@empType;
END
有人能帮忙吗。提前谢谢。
我使用的是sql server 2014和vs2015。我的猜测是,在执行查询时,C中的
deptName
值为null
。在这种情况下,您应该传递DBNull.Value
以将null作为参数值:
var param = cCommand.Parameters.Add("@deptName", SqlDbType.NVarChar, 200);
param.Value = deptName ?? DBNull.Value;
从您的过程中,我看到您与空字符串进行比较,所以使用
??string.Empty
以满足该条件。是的,您是对的,C#中的deptName等于null。但它并不总是空的。若用户想要为过滤设置任何值,那个么我必须在deptName上应用过滤器。现在这个选择不重要了。现在您有了null
您需要将参数值设置为C#null以外的任何值以消除异常<代码>??运算符将执行此操作-如果第一个值为null
,则使用第二个值。