ACCESS / SQL: how to insert INTO / UPDATE at the same time?

Here is my situation. First of all, I do not work on a relational database, I just use access as an easy way to manipulate data. At the moment I have a lot of tables.
One main table, let it MAIN and about 10 other tables, we can name X1, X2, X3, etc. Table X1 contains elements that have property X1. Table X2 contains elements with property X2, and so on.

All Xx tables have the same fields. The MAIN table has the same fields, in addition, the fields X1, X2, etc., which are Boolean.

What I want to do:

I want to transfer the main table with data from Xx tables.
The fact is that there may be elements that have several properties, so they can appear, for example, in X1, X2, X5.

So I first tried to run this:

UPDATE MAIN
SET itemnumber = X1.itemnumber, x1 = "true";

but gives nothing. now I suppose this is logical since there are no entries in the MAIN table.

In any case, what query I can write that will do this:
If the record of table X1 does not yet exist in MAIN, add it and set the field X1 to true.
If the X1 record already exists in MAIN, update it and set the X1 field to true.

(Then I would update it to run in every table X that I have.)

INSERT INTO, , ( > _ > )

, .

1
, Xx- MAIN ( )

:

INSERT INTO MAIN.itemnumber
(select X1.itemnumber from X1
UNION ALL
select X2.itemnumber from X2)

, , , :/

, X-, UPDATE WHERE EXISTS Xx, Xx true, .

- "", ...

+3
3

, :

INSERT INTO MAIN
SELECT X1.itemnumber AS itemnumber
FROM X1
WHERE not exists (select itemnumber
from MAIN
where MAIN.itemnumber = X1.itemnumber);

Xx. .

:

UPDATE MAIN SET X1 = true
WHERE exists (select *
from X1
where X1.itemnumber = MAIN.itemnumber);

Xx.

( 24 ...)
, ...

, - ...

+1

-, , .

-, SQL . SQL Server 2008, SQL Access.

-, INSERT edit 1, . :

INSERT INTO MAIN (
  field1,
  field2,
  x1,
  x2,
  ...)
SELECT
  field1,
  field2,
  True,
  False,
  ...
FROM X1
UNION ALL
SELECT
  field1,
  field2,
  False,
  True,
  ...
FROM X2
...

field1 field2 stand-ins " ", , x1, x2, & c., , xX MAIN. SELECT, UNION, False, MAIN, , True (NB: , Boolean data type - Null in Access) xX.

, , ....

+1
if EXISTS(*SELECT STATEMENT*)
Begin 
    //Update
end
ELSE
BEGIN 
   //Insert
END
-3

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


All Articles