当我运行查询时:
INSERT INTO Table2 (p1, p2) VALUES ("test",0) WHERE EXISTS(SELECT 1 FROM Table1 WHERE id=0);
它给了我Error: near "WHERE": syntax error
问题出在哪里?
答案 0 :(得分:1)
使用VALUES
代替SELECT
:
INSERT INTO Table2 (p1, p2)
SELECT "test",0
WHERE EXISTS(SELECT 1 FROM Table1 WHERE id=0)
答案 1 :(得分:0)
您可以直接使用SELECT
语句:
INSERT INTO Table2 (p1, p2)
SELECT DISTINCT "test", 0
FROM Table1
WHERE id = 0;
答案 2 :(得分:0)
如果需要SELECT
,请使用EXISTS
:
INSERT INTO Table2 (p1, p2)
SELECT p1, p2
FROM (SELECT 'test' as p1, 0 as p2) x
WHERE EXISTS (SELECT 1 FROM Table1 t1 WHERE t1.id = x.p2);
答案 3 :(得分:0)
如果仅当在表1中具有id = 0时才尝试在表2中插入这些值,为什么不使用IF?
IF EXISTS (SELECT 1 FROM Table1 WHERE id=0)
BEGIN
INSERT INTO Table2 (p1, p2) VALUES ("test",0);
END