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

I have the following trigger in a table that redirects data and includes data from two other tables based on LEFT OUTER JOIN.

If i.ndl_DeviceID does not exist in BBOwnerMap, then this column will be null, which is great.

What I want to do if i.ndl_DeviceID does not exist in BBOwnerMap, then I want to insert it there and return the received BBOwnerMap.OwnerID

The 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

The BBOwnerMap table looks 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 change this would be greatly appreciated.

Thank.

+3
source share
1 answer

. , , , . SQL Server. LEFT JOINs, , NOT EXISTS where:

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
+2

Source: https://habr.com/ru/post/1778278/


All Articles