lem*_*unk 1 c# sql sql-server-2008
使用SQL Server 2008,WinForms C#.NET 4.5,Visual Studio 2012.
我有一个查询当前使用来自a的一些信息更新表GridView.
下面是调用存储过程的代码:
public void UpdateMain(string part, int? pareto)
{
try
{
using (SqlConnection AutoConn = new SqlConnection(conn32))
{
AutoConn.Open();
using (SqlCommand InfoCommand = new SqlCommand())
{
using (SqlDataAdapter infoAdapter = new SqlDataAdapter(InfoCommand))
{
InfoCommand.Connection = AutoConn;
InfoCommand.CommandType = CommandType.StoredProcedure;
InfoCommand.CommandText = "dbo.updateMain";
InfoCommand.Parameters.AddWithValue("@part", part);
InfoCommand.Parameters.AddWithValue("@pareto", pareto);
InfoCommand.CommandTimeout = 180;
InfoCommand.ExecuteNonQuery();
}
}
}
}
catch (Exception e)
{
//MessageBox.Show("Error in connection :: " + e);
}
}
Run Code Online (Sandbox Code Playgroud)
这是SQL:
ALTER PROCEDURE [dbo].[updateMain]
@part varchar(255),
@Pareto int
as
UPDATE dbo.ParetoMain
SET NewPareto = @Pareto
WHERE Part = @part
Run Code Online (Sandbox Code Playgroud)
没有什么花哨的,你可以看到.我Newpareto遇到的问题是没有值,所以我需要它来允许空值.我确保该表允许空值.在我的C#代码中,我确保使用nullable int,但是当我运行代码时,我得到错误:
异常:抛出:"过程或函数'updateMain'需要参数'@Pareto',这是未提供的." (System.Data.SqlClient.SqlException)
抛出了System.Data.SqlClient.SqlException:"过程或函数'updateMain'需要参数'@Pareto',这是未提供的."
那么如何阻止此错误并将null置于表中?
问题是参数是预期的,但如果可以为空值则不添加null.您需要通过以下方式解决此问题:
DBNull.Value如下:InfoCommand.Parameters.AddWithValue("@Pareto", (object)pareto ?? DbNull.Value);@Pareto int = null如果要使参数可选,则存储过程可能如下所示:
ALTER PROCEDURE [dbo].[updateMain]
@part varchar(255),
@Pareto int = null
as
UPDATE dbo.ParetoMain SET NewPareto =@Pareto WHERE Part = @part
Run Code Online (Sandbox Code Playgroud)
编辑
我从你接受的答案中得出它,object因为类型不匹配的问题.为了完整起见,我正在修复我的答案.
| 归档时间: |
|
| 查看次数: |
1066 次 |
| 最近记录: |