【问题标题】:How to check if anything was inserted with INSERT SELECT (T-SQL)如何检查是否使用 INSERT SELECT (T-SQL) 插入了任何内容
【发布时间】:2011-03-15 06:19:21
【问题描述】:

我有一个插入语句:

insert into parentTbl
select firstId, secondId, thirdId, dateTm
from importTbl
where codeId = @codeIdParam

我需要可靠地确定该插入是否插入了任何内容。理想情况下,我想将 @insertedCount 变量设置为插入的行数,即使是 0。

我目前正在使用:

set @insertedCount = @@ROWCOUNT

但这似乎只获得了最后插入的行数 - 问题是如果 INSERT SELECT 语句没有插入任何内容,@@ROWCOUNT 不会返回 0。

【问题讨论】:

  • 您的插入语句是否位于循环或游标中?

标签: tsql select insert rowcount


【解决方案1】:

您可以尝试使用OUTPUT 子句,该子句每插入一行返回一行;类似:

insert into parentTbl
output inserted.firstId
select firstId, secondId, thirdId, dateTm
from importTbl
where codeId = @codeIdParam

这将为您提供包含每个插入行的 firstIds 的结果集,然后您可以对其进行计数。
一种方法是 output into 一个 table-var,然后在最后做一个 select count(*) from @tableVar 以获得你的插入计数。

【讨论】:

  • 最终,我采用了 INSERT SELECT 语句的 SELECT 并将其设置为将 COUNT(*) 返回到变量 - 当然,这发生在现在已包装的 INSERT SELECT 之前在 IF 块中。
猜你喜欢
  • 1970-01-01
  • 2013-12-29
  • 1970-01-01
  • 1970-01-01
  • 2021-12-17
  • 1970-01-01
  • 1970-01-01
  • 2019-11-12
  • 1970-01-01
相关资源
最近更新 更多