3

有没有办法在我的连接关闭后使用 SQL Server 上的 JDBC 创建一个全局临时表?

我发现如果我使用 JTDS JDBC 驱动程序创建一个全局临时表,它在我的连接关闭后不存在:

String sql = "CREATE TABLE ##foobar([name] [nvarchar](50) NOT NULL)";
Statement stmt = connection.getConnection().createStatement();
stmt.execute(sql);

我想要的是一个对每个人都可见的表,并且将在连接之间持续存在,直到服务器重新启动。

4

2 回答 2

0

您可以使用永久表、视图和登录触发器创建与 Oracle 样式临时表具有相似行为的内容:

create table dbo._Data (
    Session int not null constraint DF__Data DEFAULT (@@SPID),
    ColumnA int not null,
    ColumnB int not null
)
go
create view dbo.Data (
    ColumnA,
    ColumnB
)
with schemabinding
as
    select
        ColumnA,
        ColumnB
    from
        dbo._Data
    where
        Session = @@SPID
with check option
go
create trigger T_Data_Logon_Cleardown
ON ALL SERVER
FOR LOGON
AS
    delete from Database.dbo.Data
go

然后,您对dbo.Data“表”执行所有操作。

This has the characteristics that each session's rows are isolated, and if you disconnect and reconnect, the "table" will be empty.

What you don't get is an automated clearing of rows on transaction boundaries (if that's your preferred option - you'll have to do a manual delete). Nor is it exactly similar, since rows will remain in the table until a new session claims an old session ID (so cleanup occurs later, if at all). But from the client perspective, it may be "close enough".

于 2012-09-26T07:17:05.440 回答
0

Local temporary tables are visible only to their creators during the same connection to an instance of SQL Server as when the tables were first created or referenced. Local temporary tables are deleted after the user disconnects from the instance of SQL Server. Global temporary tables are visible to any user and any connection after they are created, and are deleted when all all connections that have referenced them have closed (see the MSDN docs)

In this case what I need is a Tempdb permanent tables that is visible to everyone, and is deleted when the server is restarted:

CREATE TABLE tempdb..foobar([name] [nvarchar](50) NOT NULL)
于 2012-09-26T21:05:42.263 回答