Dynamically generated Tempary tables

  • Declare @Table1Query nvarchar(512)

    Set @Table1Query = 'Create Table #Table1' + 

    '(

     Column1 nvarchar(255), 

     Column2 nvarchar(255),

     Column3 nvarchar(255),

     Column4 nvarchar(255)

    )'

    Exec sp_executesql @Table1Query

    On execution of this dynamic query the server returns message "The commands completed successfully". But when i try to select from this table it raises error.

    Select * From #Table1    --> this query raises following error

    Server: Msg 208, Level 16, State 1, Line 1

    Invalid object name '#Table1'.

    Can some one figure out wats the problem ??

    Regards,

    Hatim Ali.

  • Look at the site I've mentioned here http://www.sqlservercentral.com/forums/shwmessage.aspx?forumid=8&messageid=129464

    There you'll find the explanation why this won't work.

    --
    Frank Kalis
    Microsoft SQL Server MVP
    Webmaster: http://www.insidesql.org/blogs
    My blog: http://www.insidesql.org/blogs/frankkalis/[/url]

  • One way to work around the limitation of #table temp tables only being avilable in the process that creates them is to create global temp tables ##table or just use create table to create normal tables in tempdb.

    Be aware that you will need to drop the tables after you are through with them.

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply