get new SQL record ID

前端 未结 8 2040
南方客
南方客 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:11

    There are three ways to get the the last identity in sql.

    They were already mentioned by others, but for completeness:

    • @@IDENTITY - can also return ids created in other objects in the same scope (think triggers)
    • IDENT_CURRENT - limited to a table, but not to your scope, so it can give bad results for busy tables
    • Scope_Idenity() - Limited to the scope of the request. Use this 99% of the time

    Additionally, there are three ways to take that ID and return it to your client code:

    • Use an output parameter in a stored procedure

      INSERT INTO [MyTable] ([col1],[col2],[col3]) VALUES (1,2,3); 
      SELECT @OutputParameterName = Scope_Identity();
      
    • Use a return value.

      INSERT INTO [MyTable] ([col1],[col2],[col3]) VALUES (1,2,3); 
      Return Scope_Identity();
      
    • Select the id into a result set. For example, your sql statement would look something like this:

      Dim ResultID As Integer
      Dim strSQL As String
      strSQL = "INSERT INTO [MyTable] ([col1],[col2],[col3]) VALUES (1,2,3); SELECT Scope_Identity();"
      rsResults.Open strSQL, oConn
      ResultID = rsResults("ID")
      

    Unfortunately (or fortunately, from my point of view) my Classic ASP it too far gone to show examples of the first two from client code.

提交回复
热议问题