Session-global temporary tables in SQL Server

后端 未结 4 2018
無奈伤痛
無奈伤痛 2021-01-16 15:31

In SQL Server, temporary tables with a name like #temp has a local scope. If you create them in your session, everything in your session can see them, but not outside your s

相关标签:
4条回答
  • 2021-01-16 16:07

    Another kludge that may work for you - it depends on how many temp tables are involved here.

    Create your temp tables as real tables, with an extra column called SPID, defaulting to @@SPID.

    Then create a view that accesses these tables, but filters based on the @@SPID value. All operations that take place through this view should look as if they're isolated on a per-session basis. E.g.:

    create table temp_Boris (
        SPID int default @@SPID,
        ColA int,
        ColB varchar(10)
    )
    go
    create view vBoris
    as
        select ColA,ColB from temp_Boris where SPID = @@SPID
    go
    

    Then, on one connection, run the following:

    insert into vBoris(ColA,ColB)
    select 10,'abc' union all
    select 20,'def'
    go
    select * from vBoris
    

    And on another connection, run the following:

    insert into vBoris(ColA,ColB)
    select 10,'abc' union all
    select 20,'def'
    go
    select * from vBoris
    select * from temp_Boris
    go
    delete from vBoris
    go
    select * from vBoris
    select * from temp_Boris
    

    And you'll see that each connection is able to treat "vBoris" somewhat like a temp table - of course, you might need to add additional routines around this (and possibly more columns) to clear the table of old/stale results.

    Okay, I'll admit, it feels ugly too.

    0 讨论(0)
  • 2021-01-16 16:09

    Could you not create the table when you start the session, then execute the stored proc, then do whatever else you want to do to the table after the stored proc executes?

    0 讨论(0)
  • 2021-01-16 16:09

    You'd cache the results in your client code if the data is not meant to be persisted or shared. If it is meant to be persisted or shared, then you'd use a normal table.

    In other words, from a result and calling perspective a stored procedure call should be stateless. If the data is private to the session then it should be in the client. This avoids using server resourcey and means you don't need to keep the connection open between calls

    Saying that, you can persist small amounts (128 bytes) of data on an open connection for that connection only using CONTEXT_INFO.

    0 讨论(0)
  • 2021-01-16 16:23

    i dont think theres an out of the box solution in SQL server for what you require. i think the only way is to mange it yourself. is it acceptable to you create a normal table with some suffix instead of using the blobal table (where you have contorl over its full name)? since the global tables go to the tempdb, this will also help you isolate data to your database as a side effect.

    0 讨论(0)
提交回复
热议问题