Friday, March 9, 2012

Inserts....

Hi..
I have a problem...
I have a temporary table and I'm traying to do this...
create table #tmp
( valor varchar(100),
valor1 varchar(100),
valor2 varchar(100)
)

declare @.cmd varchar(500)

select @.cmd = 'Select valor, valor2 from mytable)

insert into #tmp(valor, valor2)
exec(@.cmd)

select valor, valor2 from #tmp

but I have an error... 'Invalid object name #tmp'

why??other than a few typos everything looked good try this:

if object_id('mytable') is not null drop table mytable
if object_id('tempdb..#tmp') is not null drop table mytable

create table mytable(
valor varchar(100),
valor1 varchar(100),
valor2 varchar(100))

insert into mytable values('A','B','C')
insert into mytable values('D','E','F')
insert into mytable values('G','H','I')
insert into mytable values('J','K','L')

create table #tmp(
valor varchar(100),
valor1 varchar(100),
valor2 varchar(100))

declare @.cmd varchar(500)

select @.cmd = 'Select valor, valor2 from mytable'

insert into #tmp(valor, valor2)
exec(@.cmd)

select valor, valor2 from #tmp|||If you have this code inside of a stored proc it should work, otherwise it won't because your temporary table is local not global. (local temporary tables are visible only in the current sesion).
Try using:
CREATE TABLE ##tmp

or

CREATE TABLE tempdb..tmp

see "tempoary tables" in BOL for more details

No comments:

Post a Comment