【问题标题】:Creating temp tables in sybase在sybase中创建临时表
【发布时间】:2019-01-22 12:29:39
【问题描述】:

我在 Sybase db 中创建临时表时遇到了问题。我们有一个 sql,我们在其中创建一个临时表,插入/更新它并在最后从它中选择 * 得到一些结果。我们使用 spring jdbc tmplate 从服务层调用这个 sql。第一次运行正常,但下一次运行失败并出现错误

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

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

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

create table #temp_table(
...
)

我在这里缺少什么?

【问题讨论】:

    标签: sybase temp-tables sap-ase


    【解决方案1】:

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

    您提供的代码 sn-p 在作为 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 所建议的,解决此问题的一种方法是将您的代码 sn-p 分成两个单独的批次,例如:

    -- 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
    

    【讨论】:

      【解决方案2】:

      您真的很接近,但临时表之前也需要使用数据库名称。

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

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

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

      【讨论】:

      • 如果数据服务器已经配置了多个临时数据库并且当前用户/会话被分配了一个不是tempdb的临时数据库,这将不起作用
      • 我猜不是,但是你可以为每个 tempdb 添加一个。否则你有更好的解决方案吗?
      • 您可以使用 db_name()@@tempdbid 的组合来构建动态的 '.#Results' 字符串......但这有点矫枉过正,因为 object_id('#Results') 应该更多足以获取临时表的对象 ID
      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2010-09-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-21
        • 1970-01-01
        • 1970-01-01
        • 2012-01-10
        • 2011-05-03
        相关资源
        最近更新 更多