0

So, I'm trying to insert values into a table if those values aren't already present. I know this works - see https://stackoverflow.com/a/53629298/1525594

INSERT INTO table_name (name, address, tele)
SELECT * FROM (SELECT 'Nazir', 'Kolkata', '033') AS tmp
WHERE NOT EXISTS (
    SELECT name FROM table_name WHERE name = 'Nazir'
) LIMIT 1;

But what I'm wondering is: can I use VALUES(name) function so I don't have to specify the name twice? When I try it, I get Incorrect syntax near the keyword 'VALUES'.

INSERT INTO table_name (name, address, tele)
SELECT * FROM (SELECT 'Nazir', 'Kolkata', '033') AS tmp
WHERE NOT EXISTS (
    SELECT name FROM table_name WHERE name = VALUES(name)
) LIMIT 1;

Why does this error, and is this possible, or no?

I was hoping this was possible because (different question) I would like to do a multi-row insert - perhaps using UNION to select multiple rows?

(Edit): Not a duplicate - please read the question. This question asks about inserting string values into a table without selecting them from another table, and it asks very specifically how to reference those insertion values inside the WHERE NOT EXISTS statement.

coderMe
  • 2,099
  • 3
  • 18
  • 20

1 Answers1

0

You could use refer to that column inside NOT EXISTS:

INSERT INTO table_name (name, address, tele)
SELECT * 
FROM (SELECT 'Nazir', 'Kolkata', '033') AS tmp(name, address, tele)
WHERE NOT EXISTS (
    SELECT name FROM table_name WHERE name = tmp.name
);

I would rewrite it with LEFT JOIN:

INSERT INTO table_name (name, address, tele)
SELECT tmp.name, tmp.address. tmp.tele
FROM (SELECT 'Nazir', 'Kolkata', '033') AS tmp(name, address, tele)
LEFT JOIN table_name t 
  ON t.name = tmp.name
WHERE t.name IS NULL;
Lukasz Szozda
  • 162,964
  • 23
  • 234
  • 275
  • 1
    Thank you! I just found this myself on the docs: https://learn.microsoft.com/en-us/sql/t-sql/language-elements/exists-transact-sql?view=sql-server-2017 Edit your answer to include the column aliases and I will accept. :) – coderMe Dec 20 '18 at 15:49
  • @coderMe I've already added column aliases `tmp(name, address, tele)` – Lukasz Szozda Dec 20 '18 at 15:50
  • :) So you did. I hadn't noticed at first, because I didn't know you could do it like that. Sweet! – coderMe Dec 20 '18 at 15:56