从 table1 和 table2 中选择不同的值,然后将它们插入 table3

Selecting distinct value from table1 and table2 and then inserting those in table3

这是我正在使用的声明。

insert into Course_Data (Branch, CC, C_Title, Sem, Credits) 
values 
(select distinct from (select * from Course_Data)
 union
(select * from TEMP1) a order by a.CC)

我遇到错误:

Incorrect syntax near the keyword 'select'. Incorrect syntax near 'a'.

课程_数据:

Branch |  CC  |  C_Title   |   Sem   | Credits 
CS       sub1    Networks      3rd     4:1:1=6 

温度:

 Branch |   CC   |   C_Title   |   Sem   | Credits
   MCA     sub1     Compuuters     3rd      4:1:1=6 
   CS      sub1     Networks       3rd      4:1:1=6 

这是2个table,所以执行查询后,我必须将MCA分支数据获取到Course_Data table而不复制CS分支数据。 IE Course_Data:

Branch |    CC    |    C_Title    |   Sem   | Credits 
 CS      sub1          Networks       3rd       4:1:1=6 
 MCA     sub1          Compuuters     3rd       4:1:1=6

带有 SELECT 语句的插入不需要关键字 VALUES。参见语法 MSDN。 所以你的查询将是

INSERT INTO Dist_Data (Branch,CC,C_Title,Sem,Credits) 
select * 
from 
(
    select * from Course_Data 
    union 
    select * from TEMP1
)a 
order by a.CC

在对 SELECT-INSERT 使用 * 时要小心,因为如果源 table 和目标 table 中的列数不匹配,它将抛出一个错误。所以最好像下面这样使用

INSERT INTO Dist_Data (Branch,CC,C_Title,Sem,Credits) 
select * 
from 
(
    select COL1,COL2,COL3,COL4,COL5 from Course_Data 
    union 
    select COL1,COL2,COL3,COL4,COL5 from TEMP1
)a 
order by a.COLUMNNAME

编辑:

根据您的新要求,您可以使用 EXCEPT clause/operator 来避免向您的 Course_Data table 插入重复数据。使用 EXCEPT 时列的顺序应该相同。更多关于 EXCEPT here.

查询

INSERT INTO Course_Data (Branch,CC,C_Title,Sem,Credits) 
select * 
from 
(
    SELECT Branch,CC,C_Title,Sem,Credits FROM TEMP1
    EXCEPT
    SELECT Branch,CC,C_Title,Sem,Credits FROM Course_Data
)a 
order by a.COLUMNNAME