Home > C# Snippets > C#: Insert NULL values into SQL Server database

C#: Insert NULL values into SQL Server database

16:04

Marek Śliwiński Leave a comment Print This Post  (763) Go to comments

To insert into database NULL value from C# code we can’t use just simple declaration for empty string like string textToInsert = “”; This will insert into database just empty string instead NULL value.

To handle this case you have to use special SQL type: System.Data.SqlTypes.SqlString.Null

Dummy example (do nothing special but shows the way) below:

using (SqlConnection cn = new SqlConnection(connectionString))
{
    string sqlText = "stored_procedure_name";
    using (SqlCommand cmd = new SqlCommand(sqlText, cn))
    {
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.Add("@TaskType", SqlDbType.NVarChar, 255).Value = System.Data.SqlTypes.SqlString.Null;

        try
        {
            cn.Open();
            cmd.ExecuteNonQuery();
        }
        catch (SqlException sqlEx)
        {
        }

    }
}

System.Data.SqlTypes namespace has all SQL Server types so if you need to insert NULL value then use suitable one for your column data type.

Share and Enjoy:
  • DotNetKicks
  • Digg
  • del.icio.us
  • Wikio IT
  • Google Bookmarks
  • Facebook
  • Print
  1. No comments yet.
  1. No trackbacks yet.

Subscribe without commenting