Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

select into based on a parameter

Status
Not open for further replies.

113983

Programmer
Jul 28, 2008
26
I have need to write program something like below

if @pnumber=1
begin
select * into #all from table1 where code = 9
end
else
begin
select * into #all from table1 where secondcode=99
end

when I try this I get #all already exists even though I am executing the else portion of above.

"There is already an object named '#all' in the database."


Is there a way around this?
 
Like Markros said, the table must already exist. There is a trick you can use.

Code:
[!]
select * into #all from table1 where 1=0
[/!]
if @pnumber=1
begin
  Insert Into #All Select * from table1 where code = 9
end
else
begin
  Insert Into #All select * from table1 where secondcode=99
end

The first line, in red, will create the #All table with the correct table structure, but without any rows. The subsequent insert into's will copy the correct data in to it.

-George
Microsoft SQL Server MVP
My Blogs
SQLCop
"The great things about standards is that there are so many to choose from." - Fortune Cookie Wisdom
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top