Sql 代替插入触发器 - 如果不存在则插入数据
我在一个表上有以下触发器,该触发器重定向数据并包含来自其他两个基于 LEFT OUTER JOIN 的表的数据。
如果 BBOwnerMap 中不存在 i.ndl_DeviceID,则该列将为空,这很好。
我想要做的是,如果 BBOwnerMap 中不存在 i.ndl_DeviceID,那么我想将其插入那里并返回生成的自动编号 BBOwnerMap.OwnerID
触发器如下:-
ALTER TRIGGER [dbo].[Redirect]
ON [dbo].[ndl_dump]
instead of insert
AS
BEGIN
INSERT INTO ndl_data
(ndl_Image,ndl_Text,ndl_Lat,ndl_Lng,ndl_CategoryID,ownerID)
SELECT i.ndl_Image,
i.ndl_Text,
i.ndl_Lat,
i.ndl_Lng,
ndl_config.ndl_CategoryID,
BBOwnerMap.OwnerID
FROM inserted i
LEFT OUTER JOIN
ndl_config
ON i.ndl_Category = ndl_config.ndl_CategoryName
LEFT OUTER JOIN
BBOwnerMap
ON i.ndl_DeviceID = BBOwnerMap.DeviceID
END
BBOwnerMap 表如下:-
[dbo].[BBOwnerMap](
[OwnerID] [int] IDENTITY(1,1) NOT NULL,
[DeviceID] [varchar](50) NOT NULL,
[DeviceNumber] [varchar](50) NOT NULL,
CONSTRAINT [PK_BBOwnerMap] PRIMARY KEY CLUSTERED
有关如何的任何帮助对此进行修改将不胜感激。
谢谢。
I have the following trigger on a table that redirects data and includes data from two other tables based on a LEFT OUTER JOIN.
If i.ndl_DeviceID does not exist in BBOwnerMap then that column will be null which is fine.
What I want to do is, if i.ndl_DeviceID does not exist in BBOwnerMap then i want to insert it into there and return the resulting autonumber BBOwnerMap.OwnerID
Trigger is as follows:-
ALTER TRIGGER [dbo].[Redirect]
ON [dbo].[ndl_dump]
instead of insert
AS
BEGIN
INSERT INTO ndl_data
(ndl_Image,ndl_Text,ndl_Lat,ndl_Lng,ndl_CategoryID,ownerID)
SELECT i.ndl_Image,
i.ndl_Text,
i.ndl_Lat,
i.ndl_Lng,
ndl_config.ndl_CategoryID,
BBOwnerMap.OwnerID
FROM inserted i
LEFT OUTER JOIN
ndl_config
ON i.ndl_Category = ndl_config.ndl_CategoryName
LEFT OUTER JOIN
BBOwnerMap
ON i.ndl_DeviceID = BBOwnerMap.DeviceID
END
BBOwnerMap table is like this:-
[dbo].[BBOwnerMap](
[OwnerID] [int] IDENTITY(1,1) NOT NULL,
[DeviceID] [varchar](50) NOT NULL,
[DeviceNumber] [varchar](50) NOT NULL,
CONSTRAINT [PK_BBOwnerMap] PRIMARY KEY CLUSTERED
Any help on how to modify this would be much appreciated.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该能够在触发器顶部添加另一个插入语句。永远记住,插入的表可以有多于一行,因此您处理的是集合,而不是行。代码假定 SQL Server。我喜欢找不到匹配项的 LEFT JOIN,但您可以使用 NOT EXISTS where 子句执行相同操作:
You should be able to just add another insert statement at the top of your trigger. Always remember that the inserted table can have more than one row, so you are dealing with sets, not rows. Code assumes SQL Server. I like LEFT JOINs that don't find matches, but you could do the same with a NOT EXISTS where clause: