简体   繁体   English

更改受更新影响的行数

[英]Change number of Rows Affected by Update

I am trying to achieve here is to basically override 0 rows Updated , when UPDATE is issued in-case the actual PK/UK value doesn't exist in the table.我试图在这里实现的是基本上覆盖0 行 Updated ,当 UPDATE 发出时,以防表中不存在实际的 PK/UK 值。 This is what I have done:这就是我所做的:

Actual Table:实际表:

CREATE TABLE fdrgiit.vereine( 
team numeric(10) primary key, 
punkte int not null, 
serie int not null 
); 

Dummy Table:虚拟表:

CREATE TABLE fdrgiit.dummyup 
( 
id numeric(1) PRIMARY KEY, 
datetest timestamp 
); 

Inserted records in both the tables:在两个表中插入记录:

insert into vereine(team,punkte,serie) values(1, 50, 1); 
insert into vereine(team,punkte,serie) values(2, 30, 1); 
insert into vereine(team,punkte,serie) values(3, 25, 1); 
insert into vereine(team,punkte,serie) values(4, 37, 2); 
insert into dummyup values(1, now()); 

Created the following function and trigger:创建了以下函数和触发器:

create or replace function updateover() 
returns trigger as 
$BODY$ 
begin 
if EXISTS (select 1 FROM vereine WHERE team = new.team ) then 
RETURN NEW; 
else 
UPDATE fdrgiit.dummyup set datetest=now() where id=1; 
RETURN NULL; 
end if; 
end; 
$BODY$ 
LANGUAGE plpgsql; 

create trigger update_redundancy 
before update on vereine 
for each row 
execute procedure updateover() ;

But when I execute an UPDATE like this on the , I am still get 0 rows affected但是当我在 上执行这样的 UPDATE 时,我仍然受到0 行的影响

update vereine set punkte=87 where team=5; 

Kindly review and please suggest if this is something that can be done.请查看并请建议是否可以完成此操作。

You cannot trigger anything with an UPDATE that does not affect row as triggers are only fired for affected rows.您不能使用不影响行的 UPDATE 触发任何内容,因为触发器仅针对受影响的行触发。

But you could wrap your alternative UPDATE into a function:但是你可以将你的替代UPDATE包装成一个函数:

CREATE OR REPLACE FUNCTION updateover()
  RETURNS int AS
$func$
   UPDATE dummyup
   SET    datetest = now()
   WHERE  id = 1
   RETURNING 2;
$func$  LANGUAGE sql;

... and run your UPDATE nested like this: ...并像这样运行您的UPDATE嵌套:

WITH upd AS (
   UPDATE vereine
   SET    punkte = 87
   WHERE  team = 5  -- does not exist!
   RETURNING 1
   )
SELECT 1 FROM upd
UNION ALL
SELECT updateover()
LIMIT 1;

db<>fiddle here db<> 在这里摆弄

If no row qualifies for an UPDATE , then 1st outer SELECT 1 FROM upd returns no row and Postgres keeps processing the 2nd SELECT updateover() .如果没有行符合UPDATE ,则第一个外部SELECT 1 FROM upd返回任何行并且 Postgres 继续处理第二个SELECT updateover() But if at least one row is affected, the final SELECT is never executed.但如果至少有一行受到影响,则永远不会执行最后的SELECT Exactly what you want.正是你想要的。

This updates dummyup one time if the UPDATE on vereine does not affect any rows;如果vereine上的UPDATE不影响任何行, vereine更新dummyup一次 never several times.从来没有几次。 But that's ok, since now() is STABLE for the duration of the transaction.但这没关系,因为now()在交易期间是STABLE的。

Related:有关的:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM