How can I INSERT values in SQL Server that are stored in string[] , so some of the values should be ignored in favor of the values stored in SQL Server, as default constraints in the table? What do I need to pass (e.g. NULL or something else) to use these default values?
I am currently adding all the default values to my code and it is becoming cumbersome.
Below is my code:
if (value == "") value = "0"; string insert = "INSERT INTO " + table + " (" + columns + ") VALUES (" + atColumns + ")"; using (SqlConnection connect = new SqlConnection(connection)) { using (SqlCommand command = new SqlCommand(insert, connect)) { //adds values to corresponding parameters for (int i = 0; i < table_cols.Length; i++) { command.Parameters.AddWithValue("@" + table_cols[i], table_vals[i]); } foreach (SqlParameter Parameter in command.Parameters) { if (Convert.ToString(Parameter.Value) == "") { Parameter.Value = DBNull.Value; } } connect.Open(); command.ExecuteNonQuery(); response = "Success"; return response;
If the specific Parameter.Value non-null and has a default value set by SQL Server, this code will not work with zero.
In SQL Server, this is handled by omitting the value in your insert statement (this omission causes the default value to be entered for the table, while providing null results in errors).
source share