不存在的T-SQL插入(... VALUES())

时间:2018-12-20 15:46:41

标签: sql-server tsql sql-server-2012

因此,如果这些值尚不存在,我将尝试将它们插入表中。我知道这可行-请参阅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;

但是我想知道的是:我可以使用VALUES(name)函数,这样我不必两次指定name吗?尝试时,我得到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;

为什么会出现此错误,这是可能的,还是没有?

我希望这是可能的,因为(不同的问题)我想进行多行插入-也许使用UNION选择多行?

(编辑):不重复-请阅读问题。这个问题询问有关将字符串值插入表中而不从另一个表中选择它们的问题,并且非常具体地询问如何在WHERE NOT EXISTS语句中引用这些插入值。

1 个答案:

答案 0 :(得分:0)

您可以使用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
);

我会用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;