Session-global temporary tables in SQL Server

后端 未结 4 2019
無奈伤痛
無奈伤痛 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.

提交回复
热议问题