SQL server如何遍历插入数据

需要将A表的3条数据查询出来插入B表,插入之前需要判断B表是否已经存在该条数据,存在则过滤掉,不存在则插入,需要涉及到判断,遍历等技术点,感谢大家帮忙解答!

img

insert into 的时候查一下a表不在b表中的数据就好了呀

insert into b select * from a where a.name not in (select b.name from b) ;

INSERT INTO B
SELECT CODE
,NAME
FROM A
WHERE NOT EXISTS (SELECT 1 FROM B WHERE A.CODE = B.CODE )

按code和name同时过滤

USE [test]
GO
insert into dbo.test_b 
select code,name from dbo.test_a where not exists (select 1 from dbo.test_b where test_b.code=test_a.code and test_b.name=test_a.name)

只按code过滤

USE [test]
GO

insert into dbo.test_b 
select code,name from dbo.test_a where not exists (select 1 from dbo.test_b where test_b.code=test_a.code)