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

前端 未结 8 423
失恋的感觉
失恋的感觉 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:09

    try this! syntax less lines and even more compact! don't forget to add the properties you want to add with this approach!

    cmd.Parameters.Add(new SqlParameter{SqlValue=(object)username??DBNull.Value,ParameterName="user" }  );
    
    0 讨论(0)
  • 2020-12-02 20:13

    Use DBNull.Value Better still, make your stored procedure parameters have defaults of NULL. Or use a Nullable<DateTime> parameter if the parameter will sometimes be a valid DateTime object

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

    Old question, but here's a fairly clean way to create a nullable parameter:

    new SqlParameter("@note", (object) request.Body ?? DBNull.Value);
    

    If request.Body has a value, then it's value is used. If it's null, then DbNull.Value is used.

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

    Let's say the name of the parameter is "Id" in your SQL stored procedure, and the C# function you're using to call the database stored procedure is name of type int?. Given that, following might solve your issue :

    public void storedProcedureName(Nullable<int> id, string name)
    {
        var idParameter = id.HasValue ?
                    new SqlParameter("Id", id) :
                    new SqlParameter { ParameterName = "Id", SqlDbType = SqlDbType.Int, Value = DBNull.Value };
    
        // to be continued...
    
    0 讨论(0)
  • 2020-12-02 20:29
    SqlParameters[1] = new SqlParameter("Date1", SqlDbType.SqlDateTime);
    SqlParameters[1].Value = DBNull.Value;
    SqlParameters[1].Direction = ParameterDirection.Input;
    

    ...then copy for the second.

    0 讨论(0)
  • 2020-12-02 20:29
        SQLParam = cmd.Parameters.Add("@RetailerID", SqlDbType.Int, 4)
        If p_RetailerID.Length = 0 Or p_RetailerID = "0" Then
            SQLParam.Value = DBNull.Value
        Else
            SQLParam.Value = p_RetailerID
        End If
    
    0 讨论(0)
提交回复
热议问题