我想将表2中的行复制到表1中,只要它们不存在于表1中即可。现在,我得到了一般错误Incorrect syntax near the keyword 'WHERE'.
和Incorrect syntax near the keyword 'NOT'.
DECLARE @UserID varchar(100)
SET @UserID = 'me'
INSERT INTO Table1 (Col1, Col2, Col3, Col4, Col7,
Col8, Col9, Col5, Col6)
(SELECT 2 AS [Col1], Col2, Col3, Col4, Col7,
Col8s, GETDATE() AS [Col9], @UserID AS [Col5], GETDATE() AS [Col6]
FROM Table2 AS bpt)
WHERE (SELECT (CONVERT(varchar(10), Col2) + Col3 + Col4) FROM Table2) NOT EXISTS
(SELECT (CONVERT(varchar(10), Col2) + Col3 + Col4) FROM Table1)
答案 0 :(得分:1)
您可以使用下面的查询创建要插入表1的select语句。
SELECT col1,col2
FROM table2
WHERE NOT EXISTS (SELECT col1,col2
FROM table1
WHERE table1.pk = table2.pk);
PK ---->主键
答案 1 :(得分:0)
如果您没有匹配的主键,请尝试类似
INSERT Table1 (col1,col2)
SELECT col1,col2 from
(
SELECT col1,col2 FROM table2
EXCEPT
SELECT col1, col2 FROM TABLE1
) A
答案 2 :(得分:0)
有时候,我宁愿组织MERGE
语句而不是INSERT
,即使您所做的只是插入MERGE
,实际上它们是同一回事。
在您的情况下,它使您可以像在联接中一样自然地比较每个键,而不是将字符串连接成一个大型键。
MERGE table1 AS tgt
USING (
SELECT 2 AS [Col1], Col2, Col3, Col4, Col7,
Col8, GETDATE() AS [Col9], @UserID AS [Col5], GETDATE() AS [Col6]
FROM Table2
) AS src
ON src.Col2 = tgt2.Col2 AND src.Col3 = tgt.Col3 AND src.Col4 = tgt.Col4
WHEN NOT MATCHED THEN
INSERT (Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9)
VALUES (src.Col1, src.Col2, src.Col3, src.Col4, src.Col5, src.Col6, src.Col7, src.Col8, src.Col9)
这是另一种方法,您可以将联接保留到表中并保留所有不匹配的项。可以,但是我觉得合并的逻辑更加直接。
INSERT INTO table1 (Col1, Col2, /* ... */ Col9)
SELECT src.Col1, src.Col2, /* ... */ Col9)
FROM (
SELECT 2 AS [Col1], Col2, Col3, Col4, Col7,
Col8, GETDATE() AS [Col9], @UserID AS [Col5], GETDATE() AS [Col6]
FROM Table2
) src
LEFT JOIN table1 tgt ON tgt.Col2 = src.Col2 AND tgt2.Col3 = src.Col3 AND tgt.Col4 = src.Col4
WHERE tgt.[PrimaryKey] IS NULL -- keep rows where there was no match to table1
答案 3 :(得分:0)
以原始查询为基础,以下是查询的LEFT JOIN和IF NOT EXISTS版本:
DECLARE @UserID varchar(100)
SET @UserID = 'me'
INSERT INTO Table1 (
Col1, Col2, Col3, Col4,
Col7, Col8, Col9, Col5,
Col6)
SELECT 2 AS [Col1],
Col2, Col3, Col4, Col7,
Col8s, GETDATE() AS [Col9],
@UserID AS [Col5],
GETDATE() AS [Col6]
FROM Table2 AS bpt
LEFT JOIN Table1 as exc
ON bpt.Col2 = exc.Col2
AND bpt.Col3 = exc.Col3
AND bpt.Col4 = exc.Col4
WHERE bpt.Col2 IS NULL
-- Alternate version using EXISTS:
DECLARE @UserID varchar(100)
SET @UserID = 'me'
INSERT INTO Table1 (
Col1, Col2, Col3, Col4,
Col7, Col8, Col9, Col5,
Col6)
SELECT 2 AS [Col1],
Col2, Col3, Col4, Col7,
Col8s, GETDATE() AS [Col9],
@UserID AS [Col5],
GETDATE() AS [Col6]
FROM Table2 AS bpt
WHERE NOT EXISTS (
SELECT *
FROM Table1
WHERE bpt.Col2 = exc.Col2
AND bpt.Col3 = exc.Col3
AND bpt.Col4 = exc.Col4
)
如果行不存在,我不建议插入MERGE版本,这仅仅是因为MERGE比这两个选项都慢。