在 sybase 中创建临时表

Creating temp tables in sybase

我运行遇到了在 Sybase 数据库中创建临时文件 table 的问题。我们有一个 sql,我们在其中创建一个临时 table、insert/update,并在最后从中执行 select * 以获得一些结果。我们正在使用 spring jdbc tmplate 从服务层调用此 sql。第一个 运行 工作正常,但下一个 运行s 失败并出现错误

cannot create temporary table <name>. Prefix name is already in use by another temorary table

这就是我检查 table 是否存在的方式:

if object_id('#temp_table') is not null
drop table #temp_table

create table #temp_table(
...
)

我在这里遗漏了什么吗?

可能不是很好的回应,但我也有这个问题,我有两种解决方法。 1. 在查询之前将 IF OBJECT_ID Drop Table 作为单独的执行 2. 在查询后立即执行不带 IF OBJECT_ID() 的 Drop Table。

你真的很接近,但是 temp tables 之前也需要使用数据库名称。

IF OBJECT_ID('tempdb..#Results') IS NOT NULL
  DROP TABLE #Results
GO

如果您要检查另一个数据库中的用户 table 是否存在,这将是相同的。

IF OBJECT_ID('myDatabase..myTable') IS NOT NULL
  DROP TABLE myDatabase..myTable
GO

注意:关于 BigDaddyO 的第一个建议的更多信息...

您提供的代码片段在作为 SQL 批次提交时,在执行前 被解析为单个工作单元。最终结果是,如果在提交批处理时 #temp_table 已经存在,那么 create table 命令的编译将产生错误。在以下示例中可以看到此行为:

create table #mytab (a int, b varchar(30), c datetime)
go

-- your code snippet; during compilation the 'create table' generates the error
-- because ... at the time of compilation #mytab already exists:

if object_id('#mytab') is not NULL
     drop table #mytab
create table #mytab (a int, b varchar(30), c datetime)
go

Msg 12822, Level 16, State 1:
Server 'ASE200', Line 3:
Cannot create temporary table '#mytab'. Prefix name '#mytab' is already in use by another temporary table '#mytab'.

-- same issue occurs if we pull the 'create table' into its own batch:

create table #mytab (a int, b varchar(30), c datetime)
go

Msg 12822, Level 16, State 1:
Server 'ASE200', Line 1:
Cannot create temporary table '#mytab'. Prefix name '#mytab' is already in use by another temporary table '#mytab'.

正如 BigDaddyO 所建议的那样,解决此问题的一种方法是将您的代码片段分成两个单独的批次,例如:

-- test/drop the table in one batch:

if object_id('#mytab') is not NULL
     drop table #mytab
go

-- create the table in a new batch; during compilation we don't get an error
-- because #mytab does not exist at this point:

create table #mytab (a int, b varchar(30), c datetime)
go