Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting ID after insert in SQL Server

I use this stored procedure to make insert and return the id of inserted row

ALTER PROCEDURE [dbo].[addObjective]
(
            @Name nvarchar(250)
           ,@ObjectiveGroupId int
           ,@CreatorId int
           ,@LanguageId int
           ,@isFinal bit
)
as 
insert into Objective values
(
            @Name
           ,@ObjectiveGroupId
           ,@CreatorId
           ,GETDATE()
           ,@LanguageId
           ,@isFinal
)

    select scope_identity() as Id;

But how to read the returned id using vb.net code

using this commands return -1

like image 961
Adham Avatar asked Jun 19 '26 05:06

Adham


1 Answers

I assume you're using the return value from a call to .ExecuteNonQuery() in your VB.NET code (which you're not showing us...... so I can only guess).

That's the wrong value to read - that value would return the number of rows that were affected by your last SQL statement (e.g. by an INSERT, UPDATE or DELETE).

Since your stored procedure IS returning a value - the newly inserted ID - and it's returning a single row, single column value (just the ID, nothing else), you need to read that value - e.g. by calling .ExecuteScalar() instead:

Dim newID As Integer = CInt(yourInsertCmd.ExecuteScalar())
like image 116
marc_s Avatar answered Jun 20 '26 22:06

marc_s



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!