2011-06-19 79 views
0

請考慮以下幾點:SQL 2005 - 臨時表問題

declare @abbrev varchar(20); set @abbrev=''; 
select pk_term into #t2 from #t1 where pk_term in (select distinct(fk_term) from tblabbreviations where abbreviation like @abbrev) 
select @count=count(*) from #t2 
print 'count t2='+convert(varchar(10),@count) 

假設#T1包含10行。當@abbrev爲''時,我希望#t2包含10行,或者當說@ abbrev ='av%'時,我希望包含10行或更少(通常更少)。

我嘗試這樣做:

declare @abbrev varchar(20); set @abbrev=''; 
if @abbrev <> '' 
    begin 
     select pk_term into #t2 from #t1 where pk_term in (select distinct(fk_term) from tblabbreviations where abbreviation like @abbrev) 
     select @count=count(*) from #t2 -- should be same as t1 
     print 'count t2='+convert(varchar(10),@count) 
    end 
else 
    select pk_term into #t2 from (select pk_term = null) -- ensure #t2 is created regardless 

但當然,我得到的錯誤「已存在名爲對象‘#T2’在數據庫中。」

我該如何解決這個問題?

非常感謝提前。

RGDS,馬克

回答

1

您使用CREATE TABLE #t2提前使用它,而不是將其作爲SELECT ... INTO的結果而創建的創建#T2。

例如

CREATE TABLE #t2 (
    pk_term VARCHAR(100) -- Or whatever... 
) 

IF ... 
BEGIN 
    INSERT INTO #t2 
    SELECT something... 
END 
ELSE 
BEGIN 
    INSERT INTO #t2 
    SELECT something else... 
END 
+0

謝謝。非常明顯!我有一個腦霧的時刻:) – Mark