First, I read this: How to dynamically build an insert command from Datatable in c#
But this doesn't helped me because i have multiple DataTypes (for example int
) which can't be NULL
.
I want that if a value is empty, that this would not be added to the Insert string.
Now: INSERT INTO table (col1, col2, col3, col4) VALUES ('val1', '', '', 'val4');
Goal: INSERT INTO table (col1, col4) VALUES ('val1','val4');
Alternative goal: INSERT INTO (col1, col2, col3, col4) VALUES ('val1', 'NULL', '0', 'val4');
(If integer then replace NULL
with 0
)
First I tried to edit the parameter value so if Length <= 0
then set the value to NULL
.
But this won't work for an INTEGER
.
cmd.CommandText = sql;
foreach (DataRow row in _dataTable.Rows)
{
cmd.Parameters.Clear();
foreach (DataColumn col in _dataTable.Columns)
{
var rowitem = row[col].ToString();
if (rowitem.Length <= 0)
{
cmd.Parameters.AddWithValue($"@{col.ColumnName}", "NULL");
}
else
{
cmd.Parameters.AddWithValue($"@{col.ColumnName}", row[col]);
}
}
}
cmd.ExecuteNonQuery();
In my DataBase all tables allows NULL
so that shouldn't be the problem.
It's just for the Integer.
Then I thought of getting the DataType of row[col]
so if the datatype is Int32
then reset "NULL"
with "0"
.
But if I want to check the DataType:
Debug.WriteLine(row[col].GetType());
Im only getting AllowDBNull
. So thats not the real DataType.