选择数据,将计算值设置到列中

发布于 2024-09-09 04:08:36 字数 215 浏览 1 评论 0原文

我正在从触发器内的表中选择数据(用于更新)。我选择的某些行已由启动触发器的事务更新,而某些行则没有。我想在数据集中的某处为每一行写入一个标志,该值将计算为“id IN (SELECT [id] FROM INSERTED)”。该标志将显示一行是否已使用最后一个事务更新。

在SQL中可以吗?

当然,我可以用 2 个不同的条件执行 2 个单独的查询,但触发器性能是真正的瓶颈......

I'm selecting data from a table within a trigger (FOR UPDATE). Some rows I'm selecting have been updated by a transaction, that initiated the trigger, and some rows are not. I'd like to write somewhere in the dataset a flag for every row, which value would be calculated as "id IN (SELECT [id] FROM INSERTED)". This flag would show, is a row updated with the last transaction or not.

Is it possible in SQL?

Sure, I can do 2 separate queries, with 2 different conditions, but the trigger perfomance is real bottleneck...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

月亮坠入山谷 2024-09-16 04:08:36

这是 SQL Server 的示例:

if object_id('TriggerTest') is not null
    drop table TriggerTest

create table TriggerTest (id int identity, name varchar(50), inLastUpdate bit)

insert TriggerTest (name) values ('joe'), ('barrack'), ('george'), ('dick')
go
create trigger dbo.TriggerTestDelete
on TriggerTest
after update
as begin
    declare @date datetime
    set @date = GETDATE()

    update  dbo.TriggerTest
    set     inLastUpdate = 
                 case when id in (select id from inserted) then 1 
                       else 0 
                 end
end
go
update TriggerTest set name = name where id in (1,2)
update TriggerTest set name = name where id in (1,3)
select * from TriggerTest

打印:

id    name        inLastUpdate
1     joe         1
2     barrack     0
3     george      1
4     dick        0

Here's an example for SQL Server:

if object_id('TriggerTest') is not null
    drop table TriggerTest

create table TriggerTest (id int identity, name varchar(50), inLastUpdate bit)

insert TriggerTest (name) values ('joe'), ('barrack'), ('george'), ('dick')
go
create trigger dbo.TriggerTestDelete
on TriggerTest
after update
as begin
    declare @date datetime
    set @date = GETDATE()

    update  dbo.TriggerTest
    set     inLastUpdate = 
                 case when id in (select id from inserted) then 1 
                       else 0 
                 end
end
go
update TriggerTest set name = name where id in (1,2)
update TriggerTest set name = name where id in (1,3)
select * from TriggerTest

This prints:

id    name        inLastUpdate
1     joe         1
2     barrack     0
3     george      1
4     dick        0
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文