【问题标题】:Excel VBA and ADODB: retrieve auto identity of row inserted into SQL Server from VBAExcel VBA 和 ADODB:检索从 VBA 插入 SQL Server 的行的自动标识
【发布时间】:2013-02-10 23:00:47
【问题描述】:

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

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

我想:

  1. INSERT INTO 测试(数据)值(“某事”)
  2. 检索新插入行的自动递增标识 (test.data_id)。

【问题讨论】:

标签: sql-server excel ado vba


【解决方案1】:
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)

【讨论】:

  • 太棒了,感谢我正在寻找的东西,就像魔术一样工作
  • 如果您有一个连接变量,可以将其简化为identity = cn.Execute("SELECT @@Identity")(0),而无需创建记录集。
猜你喜欢
  • 2014-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-02
  • 2013-04-03
  • 1970-01-01
  • 1970-01-01
  • 2013-03-01
相关资源
最近更新 更多