get new SQL record ID

前端 未结 8 2048
南方客
南方客 2020-12-17 19:31

How can I get back the autogenerated ID for a new record I just inserted? (Using ASP classic and MSSQL 2005)

8条回答
  •  悲&欢浪女
    2020-12-17 20:00

    Thanks all who suggested SELECT SCOPE_IDENTITY(). I was able to create a stored procedure:

    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
    

    and call the sproc using 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)
    

    I can now use resultID anytime I refer to the newly created ID.

提交回复
热议问题