SQL 2005 - 临时表问题

时间:2011-06-19 23:55:10

标签: sql-server-2005 tsql

请考虑以下事项:

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行。我希望#t2在@abbrev为'时包含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,Mark

1 个答案:

答案 0 :(得分:1)

您使用CREATE TABLE #t2在使用它之前创建#t2,而不是在SELECT ... INTO之后创建它。

e.g。

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