那么一旦运行一个查询更多使用SQL Server 2008,我有这个疑问,其作品我第一次运行它,但如果我尝试再次运行它,我得到一个错误无法在SQL
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 [email protected] or [email protected]
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 [email protected]
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 [email protected]
open MyCursor
FETCH NEXT FROM myCursor into @S
WHILE @@FETCH_STATUS = 0
begin
set @xx2='alter table ##a12 add ['[email protected]+'] varchar(5)'
exec(@xx2)
set @xx2='update a set a.['[email protected]+']=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='''[email protected]+''''
exec(@xx2)
set @xx2='update a set a.['[email protected]+']=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='''[email protected]+''''
exec(@xx2)
set @xx2='update a set a.['[email protected]+']=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='''[email protected]+''''
exec(@xx2)
set @xx2='update ##a12 set ['[email protected]+']='''' where ['[email protected]+'] =''0'''
exec(@xx2)
set @xx2='update ##a12 set ['[email protected]+']='''' where ['[email protected]+'] 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.
如果我重装我的管理工作室,它工作得很好,如果我手动删除该表它的工作原理也是如此。我曾经使用过,如果> drop语句在开始之前没有问题,但由于某种原因它现在没有采取。
为什么使用##全局临时表?为什么不是#本地的?当你完成后,你为什么不明确地丢下桌子? – 2013-02-20 15:55:07
动态SQL需要##以便与外部进行通信。 – JohnZ 2013-02-20 16:04:06
@JohnZ你应该仍然能够在你的动态Sql中引用一个本地临时表,因为你创建它的范围比你的'EXEC()'更高。 – 2013-02-20 16:08:23