可以使用distinct
关键字创建唯一条目。
select distinct
FirstName,
LastName,
CompanyName
from MyTable
因此,如果您发出以下命令,您只会将不同的值添加到新表中
insert into newTable
(
FirstName,
LastName,
CompanyName
)
select distinct
FirstName,
LastName,
CompanyName
from MyTable
where not exists (
select 1 from newTable
where newTable.FirstName = MyTable.FirstName
and newTable.LastName = MyTable.LastName
and newTable.CompanyName = MyTable.CompanyName
)
另一种向表添加不同的新值的好方法可以使用“合并”命令来完成。
merge newtable as target
using (select distinct
FirstName,
LastName,
CompanyName
from MyTable
) as source
on target.FirstName = target.FirstName
and target.LastName = target.LastName
and target.CompanyName = target.CompanyName
when not matched by target then
insert (FirstName,
LastName,
CompanyName)
values (target.FirstName,
target.LastName,
target.CompanyName);
该 MERGE
命令为您提供了控制何时同步表的选项。