Hi!
Heinrich Moser <(E-Mail Removed)> writes:
> This code (using the System.Data.SqlClient namespace)...
>
> SqlCommand c = myConnection.CreateCommand();
> c.CommandText = "INSERT INTO myTable (myField) VALUES (@myParameter)";
> c.Parameters.Add("@myParameter", myValue);
> c.ExecuteNonQuery();
>
> ...usually works perfectly fine for all kinds of myFields and all
> kinds of myValues, UNLESS
>
> - myField is of (SQL Server) data type "image" AND
> - myValue is DBNull.Value
>
> In that case I get an SQL Server error message stating that nvarchar
> is incompatible with image ("Operandentypkollision: nvarchar ist
> inkompatibel mit image").
[...]
> Is there an easy solution to this problem? I need this for a library
> function, i.e. the data type of myField is not known at run-time. Of
> course, I could string-replace @myParameter with NULL if myValue is
> DBNull.Value but that seems like a rather ugly workaround to me...
I was able to solve this problem and would like to share the solution.
The problem was already identified:
> I think I understand what is happening behind the scenes: ADO.NET
> cannot infer a useful data type from DBNull.Value so it assumes that
> it's an nvarchar, which supports implicit conversion into a lot of
> other data types, excluding (unfortunately) image.
So the challenge was just finding an SQL data type that *can*
implicitly be converted to image (and the other important data types
of course).
In my research I stumbled upon the following chart (in the middle of
the page, Section "remarks"):
http://msdn2.microsoft.com/en-us/library/ms187928.aspx
It shows that nvarchar (the data type assumed by ADO.NET when passed a
DBNull parameter without an explicit type) does not implicitly convert
to image, *but varchar does*.
So, the solution is:
SqlCommand c = myConnection.CreateCommand();
c.CommandText = "INSERT INTO myTable (myField) VALUES (@myParameter)";
if (myValue.equals(DBNull.Value))
c.Parameters.Add("@myParameter", SqlDbType.VarChar).Value = DBNull.Value;
else
c.Parameters.Add("@myParameter", myValue);
c.ExecuteNonQuery();
Thank you Morten for your help!
Greetings,
Heinzi