一尘不染

获取新的SQL记录ID

sql

如何获取刚刚插入的新记录的自动生成的ID?(使用ASP Classic和MSSQL 2005)


阅读 313

收藏
2021-03-10

共1个答案

一尘不染

感谢所有建议SELECT SCOPE_IDENTITY()的人。我能够创建一个存储过程:

USE [dbname]
GO 
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spInsert]
(
   @Nn varchar(30)
)
AS
BEGIN TRANSACTION InsertRecord 
   INSERT INTO A (Nn) 
   VALUES (@Nn) 
   SELECT NewID = SCOPE_IDENTITY()   -- returns the new record ID of this transaction
   COMMIT TRANSACTION InsertRecord

并使用VB调用存储过程:

Dim strNn '<- var to be passed'
Set cn = Server.CreateObject("ADODB.Connection") 
connectString = "DSN" 
cn.Open connectString, "user", "PW0rd" 
Set rs = Server.CreateObject("ADODB.Recordset") 
set rs = cn.Execute("EXEC [dbname].[dbo].[A] @Nn=" & strNn)
'return the value'
resultID = rs(0)

现在,只要我引用新创建的ID,就可以使用resultID。

2021-03-10