How do I insert into a table and get back the primary key value?(如何插入表并取回主键值?)
问题描述
我有一个主键设置为自动递增.
I have a primary key set up to auto increment.
我正在执行多个查询,我需要检索该主键值以用作另一个表中的外键 (IsIdentity = TRUE
).
I am doing multiple queries and I need to retrieve that primary key value to use as a foreign key in another table (IsIdentity = TRUE
).
当我执行插入查询时,有没有什么优雅的方法来取回主键值?现在我正在重新查询并获得该列中的最高值,这似乎非常糟糕.
Is there any elegant way to get back the primary key value when I do an insert query? Right now I am requerying and getting the highest value in that column which seems really hacky.
有什么建议吗?
推荐答案
insert into YourTable values (...)
使用 scope_identity() 获取新的 PK
get the new PK with scope_identity()
select scope_identity()
这篇关于如何插入表并取回主键值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何插入表并取回主键值?


基础教程推荐
- 带更新的 sqlite CTE 2022-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01