Using SQL Server 2008, I have this query which works the first time I run it, but if I try to run it again, I get an error
if (exists (select * from tempdb.INFORMATION_SCHEMA.TABLES where TABLE_NAME = '##a12'))
begin
drop table ##a12
end
else
declare @p varchar(1000)
declare @s varchar(5)
declare @xx2 varchar(2000)
set @p = '64-267-601'
select top 1 @p=ivproduct from rpiv where upc=@p or ivproduct=@p
select distinct storeid,color,wil,cast('OH' as varchar(4)) as TP into ##a12 from rpiv i, rpproducts p where i.ivproduct=p.productid and p.productid=@p
insert into ##a12 select storeid,color,wil,'Rcvd' from ##a12
insert into ##a12 select storeid,color,wil,'Sld' from ##a12 where tp='oh'
DECLARE myCursor CURSOR FOR SELECT distinct size from rpiv where ivproduct=@p
open MyCursor
FETCH NEXT FROM myCursor into @S
WHILE @@FETCH_STATUS = 0
begin
set @xx2='alter table ##a12 add ['+@s+'] varchar(5)'
exec(@xx2)
set @xx2='update a set a.['+@s+']=coalesce(b.onhand,0) from ##a12 a,rpiv b where a.tp=''oh'' and a.storeid=b.storeid and a.color=b.color and a.wil=b.wil and b.size='''+@s+''''
exec(@xx2)
set @xx2='update a set a.['+@s+']=coalesce(b.PurchasedToDate,0) from ##a12 a,rpiv b where a.tp=''rcvd'' and a.storeid=b.storeid and a.color=b.color and a.wil=b.wil and b.size='''+@s+''''
exec(@xx2)
set @xx2='update a set a.['+@s+']=coalesce(b.SoldtoDate,0) from ##a12 a,rpiv b where a.tp=''sld'' and a.storeid=b.storeid and a.color=b.color and a.wil=b.wil and b.size='''+@s+''''
exec(@xx2)
set @xx2='update ##a12 set ['+@s+']='''' where ['+@s+'] =''0'''
exec(@xx2)
set @xx2='update ##a12 set ['+@s+']='''' where ['+@s+'] is null'
exec(@xx2)
FETCH NEXT FROM myCursor into @S
End
Close myCursor
DEALLOCATE myCursor
if not exists(select * from ##a12 where wil<>'')
begin
alter table ##a12 drop column wil
select * from ##a12 order by storeid,color,tp
end
else
select * from ##a12 order by storeid,color,wil,tp
And this is the error that I get :
Msg 207, Level 16, State 1, Line 14
Invalid column name 'wil'.
Msg 213, Level 16, State 1, Line 14
Column name or number of supplied values does not match table definition.
If I reload my Management studio, it works just fine, and if I manually drop the table it works as well. I have used that if > drop statement at the start before with no problem, but for some reason it is not taking it now.
Try adding a
GO:This is happening because when the batch gets parsed on the second execution, the
wilcolumn has been dropped, and the parser doesn’t realize that it will be re-added when the temporary table is dropped and recreated.By adding the
GO, you split the batch into two… and when the second batch runs, thewilcolumn exists again.