在SQL Server中插入后获取ID

时间:2012-01-29 10:01:14

标签: sql-server vb.net stored-procedures

我使用此存储过程进行插入并返回插入行的id

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 个答案:

答案 0 :(得分:3)

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

这是错误的读取值 - 该值将返回受上一个SQL语句影响的行数(例如INSERTUPDATE或{{1} })。

由于您的存储过程 IS 返回一个值 - 新插入的DELETE - 并且它返回单行,单列值(仅ID ,没有别的),你需要阅读这个价值 - 例如通过调用ID代替:

.ExecuteScalar()

答案 1 :(得分:0)

select * from (tablename) order by (id) DESC
for x = 0 to (tablename).rows.count - 1
savedid = (tablename).rows(x).item("id").tostring
next