SQL Server 2008 を使用して、初めて実行したときにこのクエリが機能しますが、再度実行しようとするとエラーが発生します
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
そして、これは私が得るエラーです:
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 > drop ステートメントを最初に使用していましたが、何らかの理由で現在は使用していません。