Microsoft SQL Server
--
Questions
--
Followers
Top Experts
I have a table with a primary key that is 3 columns. I want to create a trigger (on update and on insert) on this table that updates a particular column on this table. I've done this successfully for tables with a 1 column primary key .... but I don't think the same logic will apply.
Below is a simplified version of my table and the syntax for my trigger. My problem is that when I do a batch insert (I insert 100 rows with the same PCode but different SPIDs), I'm afraid that on the insert of each row - it updates the column for all 100 each time. So when it inserts the last row, it will update all the rows with the timestamp of when the last one was inserted. Is my understanding correct? Am I making a mountain out of a molehill? I'm concerned that as data grows and as our batch inserts become larger .... that we will take a performance hit.
CREATE TABLE [dbo].[Apple](
[PCode] [nvarchar](50) NOT NULL,
[SPID] [int] NOT NULL,
[Month] [datetime] NOT NULL,
[LastUpdatedTimeStamp] [datetime] NULL,
[LastUpdatedBy] [nvarchar](50) NULL,
CONSTRAINT [PK_Apple] PRIMARY KEY CLUSTERED
(
[PCode] ASC,
[SPID] ASC,
[Month] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
Create TRIGGER [dbo].[t_UpdInsApple] ON [dbo].[Apple] FOR UPDATE,INSERT
AS
BEGIN
SET NOCOUNT ON;
BEGIN
UPDATE dbo.Apple
SET LastUpdatedTimeStamp = GETDATE(), LastUpdatedBy=SYSTEM_USER
WHERE pcode IN ( SELECT pcode FROM inserted )
END
END
Zero AI Policy
We believe in human intelligence. Our moderation policy strictly prohibits the use of LLM content in our Q&A threads.
Batch inserts will be much different than singleton inserts, but if you have done this in the past with a PK of 1 column, it will act the same in this case with 3 columns.
Is it because the 1000 lines (although separate) are considered one batch statement and are committed at the same time? Is the special 'inserted' system table deleted after the execution of each batch?
I added a Logger to the trigger and I get 50 distinct trigger fires from my 50 inserts, so it is acting appropriately. The GETDATE() may not be executing the way you think it should, but these are distinct trigger operations.






EARN REWARDS FOR ASKING, ANSWERING, AND MORE.
Earn free swag for participating on the platform.
Thanks for the help
Microsoft SQL Server
--
Questions
--
Followers
Top Experts
Microsoft SQL Server is a suite of relational database management system (RDBMS) products providing multi-user database access functionality.SQL Server is available in multiple versions, typically identified by release year, and versions are subdivided into editions to distinguish between product functionality. Component services include integration (SSIS), reporting (SSRS), analysis (SSAS), data quality, master data, T-SQL and performance tuning.