Multi Column Operation

I am trying to insert data into a table from another where the data does not exist yet

In the table into which I insert the data,

CREATE TABLE #T(Name VARCHAR(10),Unit INT, Id INT)
INSERT INTO #T
    VALUES('AAA',10,100),('AAB',11,102),('AAC',12,130)

In the table, I select data from

CREATE TABLE #T1(Name VARCHAR(10),TypeId INT,Unit INT, Id INT)
INSERT INTO #T1
VALUES('AAA',3,10,100),('AAA',3,10,106)

In this case, I want to choose ('AAA',3,10,106)from # T1, because the combination AAA, 106 does not exist in #T

Basically I want to populate a unique combination of names and identifiers

I tried below which does not seem to work

SELECT *
FROM #T1
WHERE NOT EXISTS(SELECT * FROM #T)
+6
source share
2 answers

You need to somehow match the two tables:

SELECT *
FROM #T1 
WHERE NOT EXISTS(SELECT * 
                 FROM #T
                 WHERE #T1.Name = #T.Name AND #T1.ID = #T.ID)

The above question essentially says: get those table entries #T1that don't have the corresponding entry in #Tthat have the same values Nameand ID.

+3

, , insert . - :

SQL - ,

: , -

INSERT INTO #T (Name, Unit, Id)
SELECT Name, Unit, Id
FROM #T1 
WHERE 
    NOT EXISTS (SELECT Name, Unit, Id FROM #T
        WHERE #T.Name = #T1.Name AND #T.Unit = #T1.Unit AND #T.Id = #T1.Id)
0

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


All Articles