Creating INSTEAD OF UPDATE trigger to update HasChanged field in 3 tables - sql

I've created a transform view that updates the master table with values from two different tables.
When doing this update, I need to change the 'HasChanged' value in all the tables for the affected records.
Ex: One row in the master table is updated with road name from one table and city name from another. The rows in the 2 tables that contained the new road name and city name must have their HasChanged value updated to 0 (from 1), as well as the master table.
For this I need to create a trigger. So far this is what I have:
CREATE TRIGGER [Transform].[trItems_HasChanged] ON [Transform].[vItems_HasChanged]
INSTEAD OF UPDATE
AS
BEGIN
SET NOCOUNT ON
CREATE TABLE #inserted
(
Id BIGINT
)
CREATE TABLE #PostnummerBy
(
Postnr BIGINT
)
CREATE TABLE #Vejstykke
(
Id BIGINT
)
INSERT INTO #Inserted (Infohub_Id)
SELECT Id FROM inserted
CREATE NONCLUSTERED INDEX ixInserted_Infohub_Id ON #Inserted (Infohub_Id)
UPDATE
InfohubStaging.Perfion.tMirror_Items
SET
Infohub_HasChanged = 0
FROM
InfohubStaging.Perfion.tMirror_Items
JOIN #Inserted i ON i.Infohub_Id = InfohubStaging.Perfion.tMirror_Items.Infohub_Id
WHERE
Infohub_HasChanged = 1
UPDATE
InfohubStaging.Nav.tMirror_PimItem
SET
Infohub_HasChanged = 0
FROM
InfohubStaging.Nav.tMirror_PimItem
JOIN #Inserted i ON i.Infohub_Id = InfohubStaging.Nav.tMirror_PimItem.InfohubId
WHERE
Infohub_HasChanged = 1
UPDATE
InfohubStaging.Ax.tMirror_Items_LiveUpdates
SET
Infohub_HasChanged = 0
FROM
InfohubStaging.Ax.tMirror_Items_LiveUpdates
JOIN #Inserted i ON i.Infohub_Id = InfohubStaging.Ax.tMirror_Items_LiveUpdates.Infohub_Id
WHERE
Infohub_HasChanged = 1
END
I am unsure how to correctly go about this. I'm aware that 2 temp tables are created when doing an update trigger (the data before and after). Since the temp tables are non-indexable, I need to create an index for them. So I need to create 3 tables, one for each of the tables who need to have their HasChanged value updated.
My expected output from this has the HasChanged value updated in the Vejstykke, PostnummerBy and Master table.

Related

Update a field in table when I'm updating a field in another table

I have 2 tables - A and B. I have a field in Table A, which can be a null or some value; and a field in table B, which can be null or some value. Both are of nvarchar type.
Now, I would like to have a sort of event listener that whenever that field in Table A changes value, I would like the same value to be appended to the start of Table B field.
If I would want to run UPDATE statement, I would write:
UPDATE B
SET B.myValueFromB = A.myValueFromA + CONVERT(nvarchar(max),B.myValueFromB)
FROM
A JOIN B on A.Ref_num = B.Task_num
WHERE A.Ref_Num = --here is the problem
I have a form in program that updates the record having specific A.Ref_num with values. End result would be whenever I update that record, a mtaching record in Table B also gets updated. How can I do something like that?
You can use a trigger for this purpose like :
CREATE TRIGGER up_update_your_table
ON Table_A FOR UPDATE
AS
--Your id field to find the corresponding record in the other table (Table B)
DECLARE #ID VARCHAR(50)
DECLARE #Value VARCHAR(50)
SELECT #ID = YourIDFieldInTableA, #Value = YourValueFieldInTableA FROM Inserted
--Inserted returns the updated row
UPDATE Table_B SET YourValueFieldInTableB = #Value WHERE YourIDFieldInTableB = ID

Inserting data into another field in another table with Trigger

I have a trigger that inserts a record value into Table1 and also inserts the same value into Table 2. Table 1 and Table 2 have the same columns.
Now i want to insert the value that is in Table 2 into a third table called user fields table, the QNo value in table 2 must be inserted into the alphanumericCol value in Table 3.
(in terminology terms as follows: trigger after insert on table 1
fetches number from table two and derives next number, then inserts
new number into table 3 and updates table two with the new number (so
that the next time trigger fires it will have the latest number).
Here is my trigger that inserts the number into Table 1 and 2:
alter trigger insertQNO
on table1
after insert as
begin
update Table1
set QNo ='Q150' + CAST(inserted.Id AS VARCHAR(4)) + '/' + RIGHT(CONVERT(VARCHAR(10),GETDATE(),103),7)
from Table1
join inserted on inserted.Id = Table1.ID;
SET IDENTITY_INSERT dbo.table2 ON;
insert into Table2 (Id, Qno)
(select ID, Qno from table1 )
end;
go
The results are the same as per the below:
Now how do i put Qno value from table 2 into Alphanumeric value in user fields table? This is the last part of my trigger but i just cant get it

how to write a trigger to stack up two columns from two different tables in sql

We have three tables:
1.CourseRequest with fields Request_id, ExecutionStartingDate, ExecutionEndDate.
2.Courselist with fields list_id ,Request_id ,Planning_id
3.CoursePlanning with fields Planning_Id and CourseLength.
Image of table structure:
I want for each time data inserted the ExecutionEndDate will be computed from ExecutionStartingDate + length and consider that the datatypes are datatime2 and int respectively with trigger.
Basically you need to do the below:
Create a trigger for insert
Compute and update the executionEndDate field as required - for the update, you will need to join all 3 tables to find the related mapping.
Something like the below query:
CREATE TRIGGER TRG_CourseRequest ON dbo.CourseRequest --Create insert trigger for table
FOR INSERT AS
BEGIN
--Get the newly inserted CourseRequest ID
DECLARE #COURSE_REQ_ID INT
SET #COURSE_REQ_ID = (SELECT Request_id FROM INSERTED)T
UPDATE CR --Update the details
SET CR = DATEADD(CR.EXECUTIONSTARTINGDATE,CP.LENGTH)
FROM CourseRequest CR
INNER JOIN COURSELIST CL
ON CR.REQUEST_ID = CL.REQUEST_ID
INNER JOIN COURSEPLANNING CP
ON CP.PLANNING_ID = CL.PLANNING_ID
WHERE
CR.REQUEST_ID = #COURSE_REQ_ID
END
I haven't compiled this in SQL server so there might be some syntax errors!

SQL Server update value in another table if value in (inserted) first table is greater

I have the following tables: (simplified for clarity)
AppWorkHeader with columns: (ProjectID (FK), ProgPercent, + 40 others not relevant)
AppProjects with columns: (ProjectID (PK), ProgPercent + 9 others not relevant)
I am trying to create a trigger that after insert, the ProgPercent value from the AppWorkHeader table updates the ProgPercent value in the AppProjects table only if it's greater than the existing value. I can get it to work with single insertions with the following:
-- Only works on single row insert
CREATE TRIGGER [dbo].[AppWorkHeader_project_trigger]
ON
[dbo].[AppWorkHeader]
AFTER INSERT AS
IF ##ROWCOUNT = 0
RETURN
SET NOCOUNT ON
-- Get the current project completion percentage from the AppProjects table
DECLARE #inserted_projectID int = (SELECT i.ProjectID FROM inserted i)
DECLARE #current_percent decimal(5,4) = (SELECT ProgPercent FROM AppProjects WHERE ProjectID = #inserted_projectID)
UPDATE AppProjects
SET ProgPercent = inserted.ProgPercent
FROM inserted
WHERE AppProjects.ProjectID = inserted.ProjectID AND inserted.ProgPercent > #current_percent
I can get multiple insertions to work with the following code. However, the greater-than part of my where clause seems to be ignored. Multiple insertions with the same ProjectID are updated to lower values.
-- Multiple row insert
CREATE TRIGGER [dbo].[AppWorkHeader_project_trigger]
ON
[dbo].[AppWorkHeader]
AFTER INSERT AS
IF ##ROWCOUNT = 0
RETURN
SET NOCOUNT ON
UPDATE AppProjects
SET ProgPercent = inserted.ProgPercent
FROM inserted
WHERE AppProjects.ProjectID = inserted.ProjectID AND inserted.ProgPercent > (SELECT ProgPercent FROM AppProjects WHERE ProjectID = (SELECT inserted.ProjectID))
I can't figure out how to get the existing value in the AppProjects table without using a variable, and I can't seem to get multiple insertions to work if I use a variable. Where am I going wrong?
For each inserted ProjectID find the maximum ProgPercent (if there are several rows inserted with the same ProjectID).
Then join table with new values to the table with old values.
CREATE TRIGGER [dbo].[AppWorkHeader_project_trigger]
ON [dbo].[AppWorkHeader]
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON;
WITH
CTE_InsertedProjects
AS
(
SELECT
inserted.ProjectID
,MAX(inserted.ProgPercent) AS MaxProgPercent
FROM inserted
GROUP BY inserted.ProjectID
)
,CTE_AllProjects
AS
(
SELECT
AppProjects.ProjectID
,AppProjects.ProgPercent AS OldProgPercent
,CTE_InsertedProjects.MaxProgPercent AS NewProgPercent
FROM
AppProjects
INNER JOIN CTE_InsertedProjects ON CTE_InsertedProjects.ProjectID = AppProjects.ProjectID
WHERE
CTE_InsertedProjects.MaxProgPercent > AppProjects.ProgPercent
)
UPDATE CTE_AllProjects
SET OldProgPercent = NewProgPercent;
END
While Tring to Update Use JOIN To match the column ProjectID from AppProjects on AppWorkHeader ..
Update AP
set AP.ProgPercent=AWH.ProgPercent
FROM AppProjects AP Left JOIN AppWorkHeader AWH on AP.ProjectID=AWH.ProjectID
Where AP.ProgPercent < AWH.ProgPercent
This will only Update those rows where ProgPercent in AppProjects is Lesser than ProgPercent in AppWorkHeader

SQL Trigger update another table

I am newbie to triggers... can anybody help me with a trigger?
I have Table:
Name | Number
I want to write a trigger when my table receives a query like
update MyTable
set Number = Number + 1
where Name = 'myname'
When this query is running, the trigger should update another table for example:
Update MyTable 2
set Column = 'something'
where Name = 'myname (above name)
Thank you very much !
You will need to write an UPDATE trigger on table 1, to update table 2 accordingly.
Be aware: triggers in SQL Server are not called once per row that gets updated - they're called once per statement, and the internal "pseudo" tables Inserted and Deleted will contain multiple rows, so you need to take that into account when writing your trigger.
In your case, I'd write something like:
-- UPDATE trigger on "dbo.Table1"
CREATE TRIGGER Table1Updated
ON dbo.table1 FOR UPDATE
AS
BEGIN
-- update table2, using the same rows as were updated in table1
UPDATE t2
SET t2.Column = 'something'
FROM dbo.Table2 t2
INNER JOIN Inserted i ON t2.ID = i.ID
END
GO
The trick is to use the Inserted pseudo table (which contains the new values after the UPDATE - it has the exact same structure as your table the trigger is written for - here dbo.Table1) in a set-based fashion - join that to your dbo.Table2 on some column that they have in common (an ID or something).
create a trigger on table 1 for update:
CREATE TRIGGER dbo.update_trigger
ON table1
AFTER UPDATE
AS
BEGIN
DECLARE #Name VARCHAR(50)
SELECT #Name=Name FROM INSERTED
Update MyTable 2
SET Column = 'something'
WHERE Name = #Name
END
GO
try this ;)