我想出了这个查询,在赞美时没有产生任何错误,但我不知道我是否可以使用这个select
语句作为value
insert into store(c1 ,artno, c3, c4, c5, c6, c7 )
select '1', a.artno, 0,0.0,null,null,null
from art a
left join store s on s.artno=a.artno
inner join status b on a.artno = b.artno
where b.state ='5'
and s.artno is null
and a.artgroup not in('63','280')
我还看到了另一种可以使用的替代方案,但不确定它是否可以用于insert
我的要求,我看到它在存储过程中实现,所以只是抓住了是否可以使用它的想法?
declare @artno as varchar(150);
declare @count as tinyint
Declare cS CURSOR For
select a.artno
from art a
left join store s on s.artno=a.artno
inner join status b on a.artno = b.artno
where b.staus ='5'
and s.artno is null
and a.artgroup not in('63','280')
Open cS
Fetch NEXT from cS into @artno
While @@FETCH_STATUS=0
select @count=COUNT(*) from store where artno=@artno
if @count=0
BEGIN
insert into store(c1 ,artno, c3, c4, c5, c6, c7 )
values('1', a.artno, 0,0.0,null,null,null)
fetch next from cS into @artno
END
close cS
deallocate cS
一些解释哪些该使用,哪些不使用以及为什么,也会对我的知识有所帮助。
游标占用大量内存且耗时。而SELECT INTO
会预先构建要插入的表格内容,并且可以在单个拉伸中完成。同样在SELECT INTO
的情况下,SQL引擎有机会优化数据获取,而在cursor
的情况下,你强制数据库按顺序获取行,并且不可能进行优化。
http://blog.sqlauthority.com/2011/08/10/sql-server-use-insert-into-select-instead-of-cursor/
通过上面的链接,它主张我的声明。
由于它没有在其他任何地方提到,因此游标还有另一个问题。 每次插入/更新数据库都需要从客户端到服务器的往返通信。
从性能的角度来看,这实际上比听起来更糟糕。 数据库通常设计为有效地将数据批量插入表中。 插入 100 行的工作量很少是插入 1 行的 100 倍。 更典型的是,它只是更长一点。
使用游标时,将强制对操作进行"序列化"。 因此,必须先完成第一行的整个操作,然后才能移动到第二行。 这会从根本上降低性能。
正如其他人所提到的,尽可能始终使用基于集的操作。 如果你不能,考虑改变问题,这样你就可以;-)