I’m performing a simple insert into an SQL database. The query is parametrised but when I call the method which performs this insert I may not always want to populate each parameter.
As follows:
using (var sqlconnection = new SqlConnection(Globals.AFWideSettings.SqlConnectionString))
{
sqlconnection.Open();
using (
var sqlcommand =
new SqlCommand(
"insert into DataActions (afuser, aftable, changetype, originaldata, newdata) values (@afuser, @aftable, @changetype, @originaldata, @newdata);",
sqlconnection))
{
sqlcommand.Parameters.Add(new SqlParameter("afuser", userActions.AfUser));
sqlcommand.Parameters.Add(new SqlParameter("aftable", userActions.AfTable));
sqlcommand.Parameters.Add(new SqlParameter("changetype", userActions.ChangeType));
sqlcommand.Parameters.Add(new SqlParameter("originaldata", userActions.OriginalData));
sqlcommand.Parameters.Add(new SqlParameter("newdata", userActions.NewData));
sqlcommand.ExecuteNonQuery();
}
sqlconnection.Close();
}
}
If I was testing for Null information coming out of the database I would do something like:
Id = getRecords.IsDBNull(0) ? -1 : getRecords.GetInt32(0)
Is there a equivalent way of doing this on sqlparameters ? I’m stumped.
(I know I could test each item individually, I just want to be efficient)
Many thanks
Okay, so the basic syntax is as follows:
Do this for all your variables, I’ve shown an example of an integer field and an nvarchar field but use whatever the datatype is. The DEFAULT NULL bit is the part that says if no value is specified, use NULL.