1

使用 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 语句没有问题,但由于某种原因它现在没有使用它。

4

1 回答 1

2

尝试添加GO

Close myCursor
DEALLOCATE myCursor
GO

if not exists(select * from ##a12 where wil<>'') 
begin

发生这种情况是因为在第二次执行时解析批处理时,该wil列已被删除,并且解析器没有意识到当临时表被删除并重新创建时它将被重新添加。

通过添加GO,您将批次分成两部分......当第二批运行时,该wil列再次存在。

于 2013-02-20T15:37:22.240 回答