I'm trying to create a trigger to copy newly added rows from one table on a different database but on the same server to another table and increment a column which only exists on the table where the new rows are being added. I'm not sure if the code is accurate and would like any feedback on how it can be improved.
CREATE TRIGGER AddReTncyTransStatement
ON [DBAdmin].[dbo].[ReTncyTransStatement]
AFTER UPDATE, INSERT
AS
BEGIN
INSERT INTO [DBAdmin].[dbo].[ReTncyTransStatement]
([ORG-CODE], [TNCY-SYS-REF], [TRANS-NO], [PROGRESS-RECID])
SELECT
[ORG-CODE],
[TNCY-SYS-REF],
[TRANS-NO],
[ANALYSIS-CODE] ``,
(SELECT MAX([PROGRESS-RECID])
FROM [DBAdmin].[dbo].[ReTncyTransStatement]) + 1 AS RECID
FROM
[SQLViewsPro2EOD].[dbo].[RE-TNCY-TRANS]
END;
I imagine that you have a table called [RE-TNCY-TRANS]
which is in [SQLViewsPro2EOD]
database and the other table which is [ReTncyTransStatement]
that resides inside the [DBAdmin]
database.
I also imagine that you want to insert a record into [ReTncyTransStatement]
each time a record inserted into [RE-TNCY-TRANS]
. So to achieve this you need to rewrite your trigger as below:
CREATE TRIGGER AddReTncyTransStatement
ON [SQLViewsPro2EOD].[dbo].[RE-TNCY-TRANS]
AFTER UPDATE, INSERT
AS
BEGIN
INSERT INTO [DBAdmin].[dbo].[ReTncyTransStatement]
(
[ORG-CODE],
[TNCY-SYS-REF],
[TRANS-NO],
[PROGRESS-RECID]
)
SELECT [ORG-CODE],
[TNCY-SYS-REF],
[TRANS-NO],
ISNULL((
SELECT MAX([PROGRESS-RECID]) FROM [DBAdmin].[dbo].[ReTncyTransStatement]
),0) + 1 AS RECID
FROM Inserted;
END;
Update
Why I used the ISNULL function?
Because at the first time, there is no record in [DBAdmin].[dbo].[ReTncyTransStatement]
table, so the MAX([PROGRESS-RECID])
will be NULL. I used ISNULL
to handle this situation.
Why I used the inserted
?
According to the Microsoft docs:
The inserted table stores copies of the affected rows during INSERT
and UPDATE statements. During an insert or update transaction, new
rows are added to both the inserted table and the trigger table. The
rows in the inserted table are copies of the new rows in the trigger
table.
Read more here:https://docs.microsoft.com/en-us/sql/relational-databases/triggers/use-the-inserted-and-deleted-tables?view=sql-server-2017