C#: Insert NULL values into SQL Server database
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.

(763)

