【问题标题】:How do I force a drop temp table command to fully drop the table?如何强制 drop temp table 命令完全删除表?
【发布时间】:2021-05-21 03:46:12
【问题描述】:

我正在编写一个脚本,只是在试验和开发。我所做的很多事情都涉及到临时表,我将在其中 select ... into #SomeTable from ...,至少在最初的实验/早期开发阶段。

然后我会看看结果,做一些改变,然后再去。但为了让我自己更轻松一些,我也有一个drop table if exists #SomeTable,所以我可以重新运行代码。到目前为止,一切都很好。但是,如果我在临时表中添加一列然后尝试访问它,我会收到错误 Invalid column name 'newColumn'。我可以通过只执行 drop 语句,然后执行整个脚本来避免错误,但我宁愿不必这样做。据我了解,有一些临时表正在缓存,我想知道这是否是罪魁祸首。无论如何,有没有办法解决这个问题?

编辑:这是一个演示问题的简短脚本。运行脚本,然后取消注释两个 cmets 并再次运行:

drop table if exists #DemoTable
select column1 = '1'
      ,column2 = '2'
--      ,column3 = '3'
into #DemoTable

select column1
      ,column2
--      ,column3
from #DemoTable

【问题讨论】:

  • 你能显示脚本或查询吗?
  • 请在问题中添加脚本,以便我们重现此错误。 Drop table 完全删除表,没有缓存。
  • 是的,这很奇怪,所以我们需要查询。也许排序规则将列名更改为接近但不同的名称?如果你select * 看到新专栏了吗?
  • 这能回答你的问题吗? There is already an object named '#dirs' in the database error message even though I'm checking and dropping the temp table如果你在一个批次中有两次相同的名字,那么你会得到错误
  • @George select * 确实显示了新列,这可能指向一些解析器优化/懒惰?如果这很重要,我正在使用 SSMS。

标签: sql-server tsql temp-tables


【解决方案1】:

在 SSMS 中,您只需添加 GO 语句即可将代码分成 2 批。 这样,drop 在脚本的第二部分检查错误之前执行。

drop table if exists #DemoTable
GO

select column1 = '1'
      ,column2 = '2'
--      ,column3 = '3'
into #DemoTable

select column1
      ,column2
--      ,column3
from #DemoTable

【讨论】:

    【解决方案2】:

    我已尝试按照问题中提到的步骤进行操作。

    请使用 Northwind 数据库查找以下查询示例。 向临时表添加了一个新列,并成功更新了它。

    -- Create the temporary table #temp_Employees from a physical table called 'Employee' in schema 'dbo' in database 'Northwind'
    SELECT EmployeeID, FirstName, LastName , BirthDate
    INTO #temp_Employees
    FROM [Northwind].[dbo].[Employees]
    
    -- SELECT data from temptable '[#temp_Employees]' 
    SELECT * FROM #temp_Employees;
    
    -- Add a new column '[City]' to table '[#temp_Employees]' 
    ALTER TABLE #temp_Employees 
        ADD [City] NVARCHAR(15)  NULL
    GO
    
    -- SELECT data from temptable '[#temp_Employees]' 
    SELECT * FROM #temp_Employees;
    
    -- UPDATE the new column '[City]' in the table '[#temp_Employees]' 
    UPDATE T
    SET  T.[City]=E.[City]
    FROM #temp_Employees T INNER JOIN [Northwind].[dbo].[Employees] E ON T.EmployeeID=E.EmployeeID;
    
    -- SELECT data from temptable '[#temp_Employees]' 
    SELECT * FROM #temp_Employees;
    
    -- Drop the temptable if it already exists
    IF OBJECT_ID('tempDB..#temp_Employees', 'U') IS NOT NULL
    DROP TABLE #temp_Employees;
    GO
    
    -- SELECT data from temptable '[#temp_Employees]' 
    SELECT * FROM #temp_Employees;
    
    

    谢谢。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-05
      • 2012-09-29
      相关资源
      最近更新 更多