sql-server - Perl, SQL Server use of @@IDENTITY
问题描述
I have a SQL Server table with an identity column, set to autoincrement.
Coded in Perl, the insert in the code below works fine, in the while loop the fetchrow_array()
call returns no data in the @row array.
How do I best retrieve the identity value for use in subsequent SQL statements?
my $term_sql = "INSERT INTO reminder_term(site, name, description, localization) OUTPUT \@\@IDENTITY VALUES(?,?,?,?)";
my $t_stmt = $dbh->prepare($term_sql);
...
$t_stmt->execute($site, $name, $description, $localizer);
while (@row = $t_stmt->fetchrow_array()) {
$referential_key = $row[0];
}
解决方案
避免使用 @@IDENTITY 值,因为它在存在触发器时不可靠。
给定示例表架构...
create table [dbo].[reminder_term] (
[id] int not null identity(1,1),
[site] nvarchar(10),
[name] nvarchar(10),
[description] nvarchar(10),
[localization] nvarchar(10)
);
您可以稍微修改 OUTPUT 子句,您可以id
通过特殊inserted
行源捕获新值...
INSERT INTO reminder_term(site, name, description, localization)
OUTPUT inserted.id
VALUES(?,?,?,?)
推荐阅读
- jupyter-notebook - Jupyter:即使前一个单元失败,也可以运行下一个单元
- r - 找不到对象错误 Flexdashboard 运行时闪亮
- asp.net-core - 如何正确映射业务层中的实体?
- flutter - Flutter中如何根据StreamProvider变化调用Navigator.pushNamed
- python - 如何使用数据条件填充 pandas 数据框中的缺失值?
- python - 如何在 azure 管道中将版本转换为没有版本的字符串?
- python - Python:复制文件名中带有通配符的文件
- swift - CollectionView Cell 内的 UIButton 不会触发动作,没有任何作用
- javascript - 在几秒钟内逐渐更新状态
- android - Kotlin:停止内联线程