我使用下面的代码来检查临时表是否存在,如果它存在,则在重新创建之前删除表。只要我不改变列,它就可以工作。如果我稍后添加一个列,它会给出一个错误,说“无效列”。请让我知道我做错了什么。
IF OBJECT_ID('tempdb..#Results') IS NOT NULL
DROP TABLE #Results
CREATE TABLE #Results
(
Company CHAR(3),
StepId TINYINT,
FieldId TINYINT,
)
select company, stepid, fieldid from #Results
--Works fine to this point
IF OBJECT_ID('tempdb..#Results') IS NOT NULL
DROP TABLE #Results
CREATE TABLE #Results
(
Company CHAR(3),
StepId TINYINT,
FieldId TINYINT,
NewColumn NVARCHAR(50)
)
select company, stepid, fieldid, NewColumn from #Results
--Does not work
我认为问题是你需要在两者之间添加GO语句,将执行分开成批。作为第二个删除脚本,即IF OBJECT_ID('tempdb..#Results') IS NOT NULL drop TABLE #Results没有删除临时表作为单个批处理的一部分。你可以试试下面的脚本吗?
IF OBJECT_ID('tempdb..#Results') IS NOT NULL
DROP TABLE #Results
CREATE TABLE #Results
(
Company CHAR(3),
StepId TINYINT,
FieldId TINYINT,
)
GO
select company, stepid, fieldid from #Results
IF OBJECT_ID('tempdb..#Results') IS NOT NULL
DROP TABLE #Results
CREATE TABLE #Results
(
Company CHAR(3),
StepId TINYINT,
FieldId TINYINT,
NewColumn NVARCHAR(50)
)
GO
select company, stepid, fieldid, NewColumn from #Results
您可以截断并重用临时表,而不是删除并重新创建它
IF OBJECT_ID('tempdb..#Results') IS NOT NULL
Truncate TABLE #Results
else
CREATE TABLE #Results
(
Company CHAR(3),
StepId TINYINT,
FieldId TINYINT,
)
如果您使用的是Sql Server 2016或Azure Sql数据库,则使用以下语法删除临时表并重新创建它。更多信息请点击MSDN
语法
DROP TABLE [IF EXISTS] [database_name .][schema_name]。|
schema_name。table_name[,…]n]
查询:
DROP TABLE IF EXISTS #Results
CREATE TABLE #Results
(
Company CHAR(3),
StepId TINYINT,
FieldId TINYINT,
)
我认为问题是你需要在两者之间添加GO语句,将执行分开成批。作为第二个删除脚本,即IF OBJECT_ID('tempdb..#Results') IS NOT NULL drop TABLE #Results没有删除临时表作为单个批处理的一部分。你可以试试下面的脚本吗?
IF OBJECT_ID('tempdb..#Results') IS NOT NULL
DROP TABLE #Results
CREATE TABLE #Results
(
Company CHAR(3),
StepId TINYINT,
FieldId TINYINT,
)
GO
select company, stepid, fieldid from #Results
IF OBJECT_ID('tempdb..#Results') IS NOT NULL
DROP TABLE #Results
CREATE TABLE #Results
(
Company CHAR(3),
StepId TINYINT,
FieldId TINYINT,
NewColumn NVARCHAR(50)
)
GO
select company, stepid, fieldid, NewColumn from #Results