(resolved: see bottom)
I have the following code snippet:
Protected Sub SqlDataSource1_Inserted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceStatusEventArgs) Handles SqlDataSource1.Inserted affected = CInt(DirectCast(e.Command.Parameters('@affected'), IDbDataParameter).Value) newID = CInt(DirectCast(e.Command.Parameters('@newID'), IDbDataParameter).Value) End Sub
Where @newID is defined like this in the SQL string:
'INSERT INTO x(a,b,c) VALUES (@a,@b,@c); SELECT @affected = @@rowcount, @newID = SCOPE_IDENTITY();
The parameters are defined using ASP.NET as follows:
The strange thing about it is that this works 90% of the time, but every once and a while it throws an InvalidCastException saying that ‘Conversion from type ‘DBNull’ to type ‘Integer’ is not valid.’ Any ideas on what could be causing this value to be null? I don’t have any triggers set on the table, and the only thing my query is doing is running a plain insert into 1 table.
Edit: Based on the suggestions here, I added an affected parameter. I set a breakpoint, and affected = 1 but I still got the exception. However, I then figured out that I had SELECT @newID before SELECT @affected. I switched the order, and now @affected = 0. So it appears to be a problem with my insert statement after all. Thanks for your help!
From MSDN
Do you have a check to see if the insert has succeeded? It may be possible that the record you are trying to insert fails to insert anything for some reason, therefore the id is null.
Are there any triggers set up on the table? You may be retrieving the id from a trigger procedure using @@IDENTITY
I would suggest either using SCOPE_IDENTITY() or an output parameter to get the id