2012-01-29 102 views
3

我用这个存储过程进行插入和返回插入行的id插入后获取ID在SQL Server中

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; 

但如何使用读取使用vb.net代码

返回的ID此命令将返回-1

回答

2

我假设你在VB.NET代码中调用.ExecuteNonQuery()的返回值(你没有向我们展示......所以我只能猜测)。

这是错误的读取值 - 该值将返回受上次SQL语句影响的行数(例如,INSERT,UPDATEDELETE)。

由于存储过程IS返回一个值 - 新插入的ID - 和它返回一个单列,单独列的值(只是ID,没有别的),你需要阅读该值 - 例如通过调用.ExecuteScalar()代替:

Dim newID As Integer = CInt(yourInsertCmd.ExecuteScalar()) 
0
select * from (tablename) order by (id) DESC 
for x = 0 to (tablename).rows.count - 1 
savedid = (tablename).rows(x).item("id").tostring 
next