跪求复杂SQL语句!!!
如何从A表中查出B表中按条件不存在的记录,然后在更根据上一步的查询结果往C表中INSERT同样数目的记录!!急用,求高手!!!
------解决方案--------------------insert into c
select a.* from a left join b on a.id=b.id where b.id is null
--假设a,b两表之间通过id关联
------解决方案--------------------declare @ta table(id int,name varchar(10))
declare @tb table(id int,name varchar(10))
declare @tc table(id int,name varchar(10))
insert @ta
select 1, 'abc ' union all
select 2, 'efg ' union all
select 3, 'hij '
insert @tb
select 1, 'x ' union all
select 4, 'y ' union all
select 5, 'z '
----查看b表中不存在的记录
SELECT a.id,a.name FROM @ta as a
LEFT JOIN @tb as b on a.id = b.id
WHERE b.id is null
----将b表中不存在的记录插入到c表中
INSERT @tc(id,name)
SELECT a.id,a.name FROM @ta as a
LEFT JOIN @tb as b on a.id = b.id
WHERE b.id is null
----查看c表内容
select * from @tc
/*结果
id name
----------- ----------
2 efg
3 hij
*/
------解决方案--------------------insert into c
select * from a
where not exists(select 1 from b where a.id=b.id)
------解决方案--------------------再问一下,管理-》作业 中可以执行存储过程吗?
job step里可以是sql语句或者执行存储过程
但具体执行时需要在job启动的时候执行