简体   繁体   中英

Trying to insert into Table A and link Table B and C but add to all if not exist

I have 4 tables:

Table A: 
  LogID (unique identifier), 
  UserID (bigint), 
  LogDate (date/time), 
  LogEventID (int), 
  IPID (varchar(36)), 
  UserAgentID (varchar(36))

Table B: 
  IPID (unique identifier), 
  IPAddress (varchar(255))

Table C: 
  UserAgentID (unique identifier), 
  UserAgent (varchar(255))

Table D: 
  LogEventID (int), 
  LogEvent (varchar(255))

I am trying to write the to Table A but need to check Table B , Table C and Table D contain data so I can link them. If they don't contain any data, I would need to create some. Some of the tables may contain data, sometimes none of them may.

Pretty much everything, really struggling

first, you do a insert into table B, C, D WHERE NOT EXISTS

example

INSERT INTO TableB (IPID, IPAddress) 
SELECT @IPPD, @IPAddress
WHERE  NOT EXISTS
       (
           SELECT *
           FROM   TableB x
           WHERE  x.IPID = @IPID
       )

then you insert into table A

 INSERT INTO TableA ( . . . )
 SELECT . . .

SQL Server doesn't let you modify multiple tables in a single statement, so you cannot do this with a single statement.

What can you do?

  1. You can wrap the multiple statements in a single transaction, if your goal is to modify the database only once.

  2. You can write the multiple statements in stored procedure.

  3. What you really probably want is a view with insert triggers on the view. You can define a view that is the join of the tables with the values from the reference tables. An insert trigger can then check if the values exist and replace them with the appropriate ids. Or, insert into the appropriate table.

The third option does exactly what you want. I find that it is a bit of trouble to maintain triggers, so for an application, I would prefer wrapping the logic in a stored procedure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM