且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 SQL Server 中插入后获取 ID

更新时间:2023-01-22 16:49:13

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

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).

这是读取错误的值 - 该值将返回受上次 SQL 语句影响的行数(例如,受 INSERTUPDATE>删除代码>).

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).

因为您的存储过程 IS 返回一个值 - 新插入的 ID - 并且它返回单行单列值(只是 ID代码>,没有别的),您需要读取该值 - 例如通过调用 .ExecuteScalar() 代替:

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())