Excel VBA 和 ADODB:从 VBA 检索插入 SQL Server 的行的自动标识

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14803623/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 19:34:23  来源:igfitidea点击:

Excel VBA and ADODB: retrieve auto identity of row inserted into SQL Server from VBA

sql-serverexcel-vbaadovbaexcel

提问by user743094

In a VBA module for Excel. Using an ADODB.Connection and this connection string:

在 Excel 的 VBA 模块中。使用 ADODB.Connection 和此连接字符串:

"Provider=SQLOLEDB;Data Source=MARS;Initial Catalog=automation;Trusted_connection=yes;"

I want to:

我想要:

  1. INSERT INTO test (data) VALUES ('Something')
  2. Retrieve the auto incremented identity (test.data_id) of the newly inserted row.
  1. INSERT INTO test (data) VALUES ('Something')
  2. 检索新插入行的自动递增标识 (test.data_id)。

回答by user743094

Dim identity as integer
Dim cn As New ADODB.Connection
Dim rs As New ADODB.Recordset

cn.ConnectionString = "whatever..."
cn.Open
cn.Execute ("INSERT INTO test(data) VALUES ('hello world')")
rs.Open "SELECT @@identity AS NewID", cn
identity = rs.Fields("NewID") 
MsgBox (identity)