Link to home
Start Free TrialLog in
Avatar of sandeep1983
sandeep1983Flag for India

asked on

How to create a Local Temp Table using command sp_executesql

Created a stored procedure with the following statments
declare @SqlQuery
@SqlQuery = 'select * into #test from dept'
execute sp_executesql @SqlQuery
select * from #test

If I execute the Stored procedure. The following error is produced
server: Msg 208, Level 16, State 1,  Procedure Test, Line 15
Invalid object name '#test'
Avatar of Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3]
Flag of Luxembourg image

you cannot. once the sql_executesql is finished, the temp table from inside the dynamic sql has gone out of scope, and the temp table is gone.
ASKER CERTIFIED SOLUTION
Avatar of Muhammad Kashif
Muhammad Kashif
Flag of Pakistan image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
What about a global temp table, so it stays in scope until connection is closed?
As Makolyte suggests, a global temp table should solve your problem.  You use it like this:

declare @SqlQuery nvarchar(1000)
set @SqlQuery = 'select * into ##test from dept'
execute sp_executesql @SqlQuery
select * from ##test

Please note that I made a couple of syntax corrections to your statements.
Avatar of sandeep1983

ASKER

Thanks. it is working fine