I\'m trying to populate a temp table based on the result of a condition in SQL 2005. The temp table will have the same structure either way, but will be populated using a d
Answering 8 years late, but I'm surprised nobody thought of:
select * into #MyTempTable from...
where 1=2
IF -- CONDITION HERE
insert into #MyTempTable select...
ELSE
insert into #MyTempTable select...
Simple, quick, and it works. No dynamic sql needed
this code may help you
--creating temptable using columns of two existing tables
--you can create your temp table Using other methods
select top 0 VI.*,VU.FullName
into #mytemptable
from dbo.Items VI inner join
dbo.Users as VU
on VU.Id=VI.Id
--insert your data base on your condition
if(i<2) --First Condition
begin
INSERT INTO #mytemptable
SELECT VI.*,VU.FullName
from dbo.Items VI inner join
dbo.Users as VU
on VU.Id=VI.Id
end
Else if(2<i) --Second Condition
begin
INSERT INTO #mytemptable
SELECT VI.*,VU.FullName
from dbo.Items VI inner join
dbo.Users as VU
on VU.Id=VI.Id
end
select * from #mytemptable --show result
drop table #mytemptable --drop table if its needed
this code works in sql server 2014 i don't know if it works in sql 2005 or not