Hi folks,
I have the following trigger, but because a trigger needs to handle multiple records, I'm not sure how to correctly handle this, in my trigger code.
Can someone please suggest how I can change the TSql below to correctly handle multiple records, instead of just a single record (as is listed, below).
Table Schema and defaults.
CREATE TABLE [dbo].[tblArticle](
[IdArticle] [int] IDENTITY(1,1) NOT NULL,
[IdArticleStatus] [tinyint] NOT NULL,
[Title] [nvarchar](200) NOT NULL,
[CleanTitle] [nvarchar](300) NOT NULL,
[UniqueTitle] [nvarchar](300) NOT NULL,
[Content] [nvarchar](max) NOT NULL
GO
ALTER TABLE [dbo].[tblArticle] ADD CONSTRAINT [DF_tblArticle_CleanTitle]
DEFAULT (newid()) FOR [CleanTitle]
GO
ALTER TABLE [dbo].[tblArticle] ADD CONSTRAINT [DF_tblArticle_UniqueTitle]
DEFAULT (newid()) FOR [UniqueTitle]
GO
Trigger, which only handles a single record ... not multiple.
ALTER TRIGGER [dbo].[ArticlesAfterInsertOrUpdate]
ON [dbo].[tblArticle]
AFTER INSERT,UPDATE
AS
BEGIN
SET NOCOUNT ON
DECLARE @IdArticle INTEGER,
@Title NVARCHAR(300),
@CleanTitle NVARCHAR(300),
@UniqueTitle NVARCHAR(300),
@NewCleanTitle NVARCHAR(300),
@CleanTitleCount INTEGER
-- Only Update the CleanTitle and UniqueTitle if *required*
-- This means, create a unique subject of the title, then check if this clean value
-- is different to the current clean value. If so, then update both clean and unique.
-- Otherwise, don't do anything (because it will include this row in the count check, below).
IF UPDATE(Title) BEGIN
-- TODO: How will this handle multiple records???
SELECT @IdArticle = IdArticle, @Title = Title, @CleanTitle = CleanTitle
FROM INSERTED
-- Create the 'Slugs'.
SET @NewCleanTitle = dbo.CreateUniqueSubject(@Title)
SET @UniqueTitle = @NewCleanTitle
IF @NewCleanTitle != @CleanTitle BEGIN
-- We need to update the clean and unique, so lets get started...
-- Grab the count :: eg. how many other _clean_ titles already exist?
-- Note: this is the _only_ reason why we have this
-- column - because it has an index on it.
SELECT @CleanTitleCount = COUNT(IdArticle)
FROM [dbo].[tblArticle]
WHERE CleanTitle = @NewCleanTitle
-- If we have some previous titles, then we need to append a number
-- to the end of the current slug.
IF @CleanTitleCount > 0
SET @UniqueTitle = @NewCleanTitle + CAST((@CleanTitleCount + 1) AS VARCHAR(10))
-- Now update the unique subject field.
UPDATE [dbo].[tblArticle]
SET CleanTitle = @NewCleanTitle,
UniqueTitle = @UniqueTitle
WHERE IdArticle = @IdArticle
END
END
END
GO
Please help!