How to pass a null variable to a SQL Stored Procedure from C#.net code

前端 未结 8 424
失恋的感觉
失恋的感觉 2020-12-02 19:41

Im calling a SQL stored procedure from a piece of C#.net code:

SqlHelper.ExecuteDataset(sqlConnection, CommandType.StoredProcedure, STORED_PROC_NAME, sqlPara         


        
相关标签:
8条回答
  • 2020-12-02 20:30

    You can pass the DBNull.Value into the parameter's .Value property:

        SqlParameters[0] = new SqlParameter("LedgerID", SqlDbType.BigInt );
        SqlParameters[0].Value = DBNull.Value;
    

    Just adjust for your two DateTime parameters, obviously - just showing how to use the DBNull.Value property value here.

    Marc

    0 讨论(0)
  • 2020-12-02 20:30

    I use a method to convert to DBNull if it is null

        // Converts to DBNull, if Null
        public static object ToDBNull(object value)
        {
            if (null != value)
                return value;
            return DBNull.Value;
        }
    

    So when setting the parameter, just call the function

        sqlComm.Parameters.Add(new SqlParameter("@NoteNo", LibraryHelper.ToDBNull(NoteNo)));
    

    This will ensure any nulls, get changed to DBNull.Value, else it will stay the same.

    0 讨论(0)
提交回复
热议问题