在SQL中无法再运行一次查询

时间:2013-02-20 15:27:50

标签: sql-server-2008

使用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.

如果我重新加载我的管理工作室,它工作正常,如果我手动删除它也可以。如果&gt;我已经使用过在开始之前删除语句没有问题,但由于某种原因它现在没有接受它。

1 个答案:

答案 0 :(得分:2)

尝试添加GO

Close myCursor
DEALLOCATE myCursor
GO

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

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

通过添加GO,您可以将批处理拆分为两个......当第二个批处理运行时,wil列再次存在。