SqlDataAdapter Fill返回异常

时间:2015-03-26 13:41:19

标签: c# sql visual-studio-2013 sql-server-2008-r2 .net-3.5

服务器端:

ALTER PROCEDURE [dbo].[POS_STORED_OBJECTS_GET_SP]
    @STORE_ID nvarchar(8)
    ,@TERMINAL_ID nvarchar(8)
    ,@OBJECT_ID bigint
AS

客户端:

SqlParameter storeID = new SqlParameter("@STORE_ID", SqlDbType.NVarChar);
storeID.Direction = ParameterDirection.Input;
storeID.Value = Properties.storeId;
SqlParameter termanalID = new SqlParameter("@TERMINAL_ID", SqlDbType.NVarChar);
termanalID.Direction = ParameterDirection.Input;
termanalID.Value = null;
SqlParameter objectID = new SqlParameter("@OBJECT_ID", SqlDbType.BigInt);
objectID.Direction = ParameterDirection.Input;
objectID.Value = null;  

SqlConnection connection = new SqlConnection(Properties.сonnectionString);
SqlCommand command = new SqlCommand("POS_STORED_OBJECTS_GET_SP", connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(storeID);
command.Parameters.Add(termanalID);
command.Parameters.Add(objectID);  

SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = command;  

DataSet dataSet = new DataSet();
adapter.Fill(dataSet);

最后, adapter.Fill 抛出异常:

  

程序或功能' POS_STORED_OBJECTS_GET_SP'期望参数   ' @ TERMINAL_ID',未提供

我做错了什么?

3 个答案:

答案 0 :(得分:0)

不要使用null作为参数值,而是尝试使用System.DBNull.Value

答案 1 :(得分:0)

您必须设置termanalID.Value = DBNull.Value而不是null。

DBNull.Value用于发送NULL值作为参数值。

您可以使用null或不设置Value属性来使用参数的默认值,但由于您未在存储过程中指定任何默认值 - 在您的特定情况下毫无意义。

objectID参数相同的故事。

请参阅MSDN以供参考。

答案 2 :(得分:0)

您还可以在数据库端将某些参数默认值设置为null。这样您就不必在客户端创建无用的参数。

服务器端:

    ALTER PROCEDURE [dbo].[POS_STORED_OBJECTS_GET_SP]
    @STORE_ID nvarchar(8)
    ,@TERMINAL_ID nvarchar(8) = null
    ,@OBJECT_ID bigint = null
    AS

客户方:

SqlParameter storeID = new SqlParameter("@STORE_ID", SqlDbType.NVarChar);
storeID.Direction = ParameterDirection.Input;
storeID.Value = Properties.storeId;

SqlConnection connection = new SqlConnection(Properties.сonnectionString);
SqlCommand command = new SqlCommand("POS_STORED_OBJECTS_GET_SP", connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(storeID);

SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = command;  

DataSet dataSet = new DataSet();
adapter.Fill(dataSet);