假设我有表A和B,表A包含30行ID,表B包含60行ID,我想通过使用不存在的地方将B.ID插入A.ID。如果表A中不存在B.ID,表B ID将被插入表A中。
INSERT INTO A(
ID)
SELECT ID
FROM B
WHERE NOT EXISTS (Select ID From A WHERE A.ID = B.ID)
我认为我的子查询存在一些问题。请告诉我如何纠正这个问题。
假设A.ID处于NVARCHAR(200)类型且B.ID处于FLOAT类型。
INSERT INTO A(
ID)
SELECT Cast(Cast(ID as Float)as Nvarchar)
FROM B
WHERE NOT EXISTS (Select ID From A WHERE A.ID = B.ID)
但仍有错误:将数据类型nvarchar转换为float时出错。
TIA!
答案 0 :(得分:2)
使用join代替子查询以获得更好的性能
INSERT INTO A(ID)
SELECT CAST(B.ID AS nvarchar(200))
FROM A RIGHT JOIN B ON A.ID = CAST(B.ID AS NVARCHAR(200)) WHERE A.ID IS NULL
答案 1 :(得分:1)
INSERT INTO A(
ID)
SELECT CAST(B.ID AS nvarchar(200))
FROM B
WHERE NOT EXISTS (SELECT 1 FROM A WHERE A.ID = CAST(B.ID AS nvarchar(200)))