Question

I am inserting data through a user-defined table type, and I am getting back the inserted identity values in incorrect order.

Here is the stored procedure:

CREATE PROCEDURE [dbo].[InsertBulkAgency](
  @AgencyHeaders As AgencyType READONLY)
AS
BEGIN
     insert into [Agency]
     output Inserted.Id
     select *,'cm',GETDATE(),'comp',GETDATE() from @AgencyHeaders
END

And here is the C# code to save the identity values:

 using (SqlCommand cmd = new SqlCommand("InsertBulkAgency", myConnection))
            {
                cmd.CommandType = CommandType.StoredProcedure;

                cmd.Parameters.Add("@AgencyHeaders", SqlDbType.Structured).Value = dt;

                myConnection.Open();
                rdr = cmd.ExecuteReader();
                while (rdr.Read())
                {
                    sample.Add(rdr["Id"].ToString());
                }
                myConnection.Close();

            }

The returned values in the list should be sequential but they are completely random. How can I retrieve back the correct order of inserted values?

Was it helpful?

Solution

Did you try adding an ORDER BY?

insert into dbo.[Agency]
 output inserted.Id
 select *,'cm',GETDATE(),'comp',GETDATE() from @AgencyHeaders
ORDER BY inserted.Id;

Or using .sort() once you have the data back in your application.

If you don't have an ORDER BY, you shouldn't expect any specific order from SQL Server. Why should the values in the list be in any sequential order, if you have just said "give me this set"? Why should SQL Server predict that you want them sorted in any specific way? And if it did assume you wanted the data sorted, why wouldn't it pick name or any other column to order by? Truth is, SQL Server will pick whatever sort order it deems most efficient, if you've effectively told it you don't care, by not bothering to specify.

Also, why are you converting the Id to a string (which will also cause problems with sorting, since '55' < '9')? I suggest you make sure your list uses a numeric type rather than a string, otherwise it will not always sort the way you expect.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top