I have came up with this query, does not produce any error while praise, but I Don’t know if I can use this select statement as the 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')
I also saw another alternative which may be used but not sure if it can be used to insert as my requirement, I saw this implemented in stored procedure so just grabbed the idea if it can be used?
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
Some explanation which to use and which not to and why, would help me for my knowledge as well.
Cursors are memory intensive and time consuming. Whereas
SELECT INTOwould have pre-constructed the table content to be inserted and can do it in a single stretch. Also in case ofSELECT INTO, SQL Engine has chance of optimizing the data fetch whereas in case ofcursor, you are forcing the DB to fetch rows sequentially and no optimization is possible.http://blog.sqlauthority.com/2011/08/10/sql-server-use-insert-into-select-instead-of-cursor/
Go through the above link which advocates my statement.