Ejecutar un disparador; actualizando otro campo
Frecuentes
Visto 64 veces
0
I have been reading up on triggers, and I don't seem to be finding an example, that handles my situation. My situation is unfortunate. The previous DBA scattered redundant data throughout our database.
I'd like to update the company name in multiple other tables once the company name has been changed in my organiz
table. I have this, but it doesn't seem to work:
CREATE TRIGGER updOrgNameTrigger
ON organiz
AFTER UPDATE
AS
IF UPDATE(Org_Name_1)
BEGIN
DECLARE @org_name varchar(256)
SET @org_name = (select Org_Name_1 from organiz)
UPDATE other_table set Org_Name_1 = @org_name
UPDATE the_other_table set Org_name_1 = @org_name
END
¿Es posible lo que estoy tratando de hacer?
1 Respuestas
1
Your current trigger assumes that an update can only ever affect a single row; it also intends to update every single row in the other two tables with an arbitrary value from the source table (not necessarily the row that was updated!). You need to use the inserted
pseudo-table to identify the row(s) that fired the trigger and to pull the new value(s) for the Org_Name_1
column. How about this version:
CREATE TRIGGER dbo.updOrgNameTrigger
ON dbo.organiz
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
UPDATE o SET Org_Name_1 = i.Org_Name_1
FROM dbo.other_table AS o
INNER JOIN inserted AS i
ON o.org_id = i.org_id;
UPDATE o2 SET Org_Name_1 = i.Org_Name_1
FROM dbo.the_other_table AS o2
INNER JOIN inserted AS i
ON o2.org_id = i.org_id;
END
GO
contestado el 22 de mayo de 12 a las 19:05
Thanks Aaron, I was unsure how to reference the inserted pseudo-table and foolishly didn't specify a what values to update. - etm124
No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas sql sql-server tsql sql-server-2005 or haz tu propia pregunta.
How are these tables related? Are you really intending to update all rows in the other two tables? Is there only one row in each of the three tables? If so I would drop the other two tables and create synonyms or views instead. - Aaron Bertrand
@AaronBertrand
organiz
tiene una clave primaria deorg_id
.other_table
ythe_other_table
Ambos tienenorg_id
as a FK. - etm124