Mark
Mark

Reputation: 717

SQL 2005 - Temp Table Issue

Please consider the following:

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)

Assume #t1 contains 10 rows. I want #t2 to contain 10 rows when @abbrev is '', or 10 rows or less (typically less) when say @abbrev='av%'.

I tried this:

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

but of course I get the error 'There is already an object named '#t2' in the database.'

How do I get around this issue?

Many thanks in advance.

Rgds, Mark

Upvotes: 0

Views: 72

Answers (1)

Will A
Will A

Reputation: 25008

You use CREATE TABLE #t2 to create #t2 ahead of using it, rather than having it created as a result of an 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

Upvotes: 1

Related Questions