开发者

Sql instead of insert trigger - insert data if does not exist

开发者 https://www.devze.com 2023-01-28 12:29 出处:网络
I have the following trigger on a table that redirects data and includes data from two other tables based on a LEFT OUTER JOIN.

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 BBOwnerMa开发者_运维百科p 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.


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:

Insert into bbownermap (deviceid, devicenumber)
Select i.ndl_DeviceID, <deviceNum>
From inserted i
  Left join bbownermap b on i.deviceid=b.deviceid
Where b.ownerid is Null
0

精彩评论

暂无评论...
验证码 换一张
取 消