T-SQL:如果不存在则插入
T-SQL: INSERT IF NOT EXISTS
我有两个 table:
people
| peopleID | Lastname | Firstname |
| -------- | -------- | --------- |
| 1 | Smith | Marc |
| 2 | Doe | John |
| 3 | Davidson | Terry |
| 4 | Meyer | Todd |
| 5 | Richards | Abe |
customers
| customerID | Lastname | Company |
| ---------- | -------- | ------------------- |
| 1 | Davidson | Wonderproducts Inc. |
| 2 | Meyer | Banana Inc. |
现在我想将 table people
的所有元素插入到 table customers
,除了姓氏等于 customers
.
所以最后 customers
应该是这样的:
| customerID | Lastname | Company |
| ---------- | -------- | ------------------- |
| 1 | Davidson | Wonderproducts Inc. |
| 2 | Meyer | Banana Inc. |
| 3 | Smith | |
| 4 | Doe | |
| 5 | Richards | |
我已经尝试过这个:
IF NOT EXISTS
(SELECT 1 FROM customers WHERE Lastname = (SELECT Lastname FROM people))
INSERT INTO customers (Lastname) VALUES (SELECT Lastname FROM people)
试试这个
INSERT INTO customers (Lastname)
SELECT P.Lastname
FROM people P
LEFT JOIN customers C ON C.Lastname = P.Lastname
WHERE C.customerID IS NULL
我有两个 table:
people
| peopleID | Lastname | Firstname |
| -------- | -------- | --------- |
| 1 | Smith | Marc |
| 2 | Doe | John |
| 3 | Davidson | Terry |
| 4 | Meyer | Todd |
| 5 | Richards | Abe |
customers
| customerID | Lastname | Company |
| ---------- | -------- | ------------------- |
| 1 | Davidson | Wonderproducts Inc. |
| 2 | Meyer | Banana Inc. |
现在我想将 table people
的所有元素插入到 table customers
,除了姓氏等于 customers
.
所以最后 customers
应该是这样的:
| customerID | Lastname | Company |
| ---------- | -------- | ------------------- |
| 1 | Davidson | Wonderproducts Inc. |
| 2 | Meyer | Banana Inc. |
| 3 | Smith | |
| 4 | Doe | |
| 5 | Richards | |
我已经尝试过这个:
IF NOT EXISTS
(SELECT 1 FROM customers WHERE Lastname = (SELECT Lastname FROM people))
INSERT INTO customers (Lastname) VALUES (SELECT Lastname FROM people)
试试这个
INSERT INTO customers (Lastname)
SELECT P.Lastname
FROM people P
LEFT JOIN customers C ON C.Lastname = P.Lastname
WHERE C.customerID IS NULL