Here’s my stored procedure
ALTER PROCEDURE dbo.spInsertNewTask
@ModuleID int,
@Task varchar(50),
@StartDate date,
@PlannedEndDate date,
@EstimatedEndDate date,
@Status int,
@Comments varchar(500),
@Started bit
AS
INSERT INTO DTasks (ModuleID, Task, StartDate, PlannedEndDate, EstimatedEndDate, Status, Comments, Started, LastUpdated)
VALUES (@ModuleID, @Task, @StartDate, @PlannedEndDate, @EstimatedEndDate, @Status, @Comments, @Started, GETDATE())
RETURN SCOPE_IDENTITY()
When I try to capture the newly created ID, all I’m getting is always 1. How to capture the New row’s ID?
newID = cmd.ExecuteNonQuery();
In fact I need this new ID for further processing.
Thanks for helping.
Instead of
ExecuteNonQuery, which returns the number of effected rows, you should useExecuteScalar, casting the returnedobjectto the correct type:For the above to work, you also need to change the SQL from returning a return value to select the value:
The code example on the page is pretty much what you are looking to do.
If you want to keep the return type, you will need to add a return type parameter to the command, execute as non-query as you currently do, then read the value of the return parameter, as described in Getting return value from stored procedure in C#.