创建唯一的 URI Slug - 这是递归触发器吗? (SQL 服务器)
这是我的表:
dbo.Posts
- PostId (IDENTITY, PK)
- Subject
- UniqueUri (NVARCHAR(350), NOT NULL)
当我创建“帖子”时,我插入一个空白UniqueUri (使用 NEWID()
内置函数)。
然后,我在“Post”表上有一个触发器:
CREATE TRIGGER [dbo].[OnAfterInsertUpdatePostTrigger]
ON [dbo].[Posts]
AFTER INSERT, UPDATE
AS
BEGIN
SET NOCOUNT ON
DECLARE @PostIds IdentityType
INSERT INTO @PostIds
SELECT PostId
FROM INSERTED
-- Create the UniqueUri's.
EXECUTE [dbo].[UpdatePostsCleanedUriUniqueUri] @PostIds
END
它调用 SPROC 来创建唯一的 Uri。
SPROC 有一些这样的代码:
UPDATE a
SET a.CleanedUri = NEWID(),
a.UniqueUri = NEWID()
FROM [dbo].[Posts] a
INNER JOIN @PostIds b ON a.PostId = b.Id
我注意到当我尝试仅插入一个帖子时,它花费了超过一分钟的时间。
我只能推断这是一个递归触发调用?
基本上,当创建/更新帖子时,我需要创建唯一的 uri(很像堆栈,用于解决问题)。
我能想到的唯一解决方案是创建另一个名为 UniqueUri's 的表,该表除了 PostId FK 和 Uri(例如 1-1)之外什么都没有,我总是试图避免这种情况。
然后存储过程将更新该表。
还有其他建议/想法吗?
Here's my table:
dbo.Posts
- PostId (IDENTITY, PK)
- Subject
- UniqueUri (NVARCHAR(350), NOT NULL)
When i create a "Post", i insert a blank UniqueUri (using the NEWID()
built-in function).
I then have a trigger on the "Post" table:
CREATE TRIGGER [dbo].[OnAfterInsertUpdatePostTrigger]
ON [dbo].[Posts]
AFTER INSERT, UPDATE
AS
BEGIN
SET NOCOUNT ON
DECLARE @PostIds IdentityType
INSERT INTO @PostIds
SELECT PostId
FROM INSERTED
-- Create the UniqueUri's.
EXECUTE [dbo].[UpdatePostsCleanedUriUniqueUri] @PostIds
END
Which calls a SPROC to create the Unique Uri's.
The SPROC has some code like this:
UPDATE a
SET a.CleanedUri = NEWID(),
a.UniqueUri = NEWID()
FROM [dbo].[Posts] a
INNER JOIN @PostIds b ON a.PostId = b.Id
I noticed when i tried to insert only a single post, it was taking over a minute.
I can only deduce this is a recursive trigger call?
Basically, when a Post is created/updated, i need to create unique uri's (much like stack, for questions).
The only solution i can think of is created another table called UniqueUri's, which would have nothing but the PostId FK and the Uri, e.g a 1-1, which i always try to avoid.
Then the SPROC would update that table.
Any other suggestions/ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
防止触发器递归触发的一种解决方案是消除触发器对列的更改:
One solution to prevent the trigger recursively firing is to eliminate changes to your columns from the trigger: